Please enable JavaScript.
Coggle requires JavaScript to display documents.
M250 - Coggle Diagram
M250
EXAM
Question number in comments. Like assignments
Perfect syntax is not essential, the meaning of the code is important.
Only use techniques taught in the module
Steams are not expected.
You can use chapter 5 concepts - you will not be penalised for it.
Part 1: 35 marks (50mins) - Java vocab, concepts (polymorphism).
Part 2: 15 marks (25 mins) - simple class or diagram.
Part 3: 25 marks (45 mins) - inheritance, overloading, polymorphism.
Part 4: 25 marks (45 mins) - maps, list, collections.
No testbed on exam day
2013-2021 - old exams at
https://www.oustudentshopt.com/past-exam-papers
Allow to practice: coding, writing, answering question
Have BlueJ open during the exam
Read whole exam before starting.
Easy questions first.
Dont upload whole project, you will get zero for that part. Upload the code asked for.
Write code to practice for the exam. Get good and quick.
learn abstract, interface, and normal classes/methods
public
class
variables could be public static final variables.
Things to review
Chapter 3
Chapter 4 - basic definitions, generic collections etc
Things to know
Method name vs method signature
Does making a method public mean that is it available to other classes?
What's the name given to the parameter name in a method signature.
Formal parameter is the placeholder.
Actual parameter is the value actually used to replace the placeholder.
operand vs operator
operator = +, -, >
operand is thing operand operates on.
Checked vs unchecked exceptions.
Checked are exceptions due to unknowable beforehand problems, like a a full disk.
Unchecked are mainly due to logical errors in code.
need to learn
composition
multiple inheritance
polymorphism
Things I do know
method signature includes method name and brackets with parameter types if any. E.g. print(String, boolean)
Overloading: when having methods or constructors with the same names but different number of parameters in each.
primitive variables are the basic variables.
Instance variables are variables declared in a class and are initialised on object creation
Instance variables are declared inside class, belong to each instance of a class, each object has its own copy of the vars.
Reference variables hold references to memory addresses to actual objects, unlike primitives which hold actual values.
Sets and list look the same from the outside, but sets dont have a set order and only allow one of the same thing.
Instance vs static method: instance method belong to the instance and cannot be called unless an object exists. Statis method belong to the class and can be called if no object exists.
Libraries contain many packages
String literal is literally a string written between these "
Always save the results of String methods because Strings are immutable
When using '+' on a string and an int, java auto converts all to string.
ArrayList can only store objects, not primitives.
Internal vs external methods calls can be distinguished by whether an object or class name is used with dot notation in front of the method name, e.g. anObject.useAMethod(). In that case, its probably and external call. Without the object and just method name, then its probably an internal call.
You cannot assign a superclass object to a subclass reference. E.g.
Child c = new Person("Tom", "Sawyer");
This will not compile
Import Statments
List/ArrayList
: import java.util.*;
Collections
List is an interface while ArrayList is a Class. ArrayList implements the List interface.
List defines what methods a list should have.
CompareTo learning conent:
https://learn2.open.ac.uk/mod/oucontent/view.php?id=2311791§ion=1.17
Be carefuls
adding to a TreeSet is a single expression and not saved to a variable because the 'add' method of TreeSet returns a boolean.
TreeSets doesnt use hashcode to sort, only compareTo
In TreeMaps, keys are unique.
Equals, hashCode, compareTo and toString are all typical methods that will be useful at some point in the development of a collection
Learn benefits of using subclasses
polymorphism and subtyping (with an explanation of why that's useful) and enhanced abstraction are expected
Random Ideas
A class should have:
constructor
setter methods
getter methods
To
declare a field,
its when you first say that such a variable actually exists and is usually done first, at the start of a class.
To
initialise a /fieldvariable
mean to assign a value to it and is usually done in the constructor part of a class.
To go
one directory up
, use "../[filename]"
ERRORS
cost = item.discount() - "
void cannot be converted to double
" - The discount method was found to not return anything, it was a setter method and therefore had void return. Hence, setting a variable to have such a method results in a variable that has void.
ConcurrentModificationException
- This happens if we try to remove an item from a collection while using a for-each loop
Use 'is' in front of getter methods that return a boolean value. Its easier to read.
NULL
means "no object"
method calls cannot be made on variables that do not reference objects. Hence, on variables which reference null.
ANNONYMOUS OBJECT
An object without a name because if a variable name were given, it would not be used for much. The usage of the variable would be short lived.
E.g. Bid bid = lot.getHighestBid();
Person bidder = bid.getBidder();
String name = bidder.getName();
System.out.println(name);
Here you can see that the variable 'bid' is almost immediately used. And in this example, it won't be used again. So, to save time,
chain method calls
is better.
E.g. System.out.println(lot.getHighestBid().getBidder().getName());
CONVENTIONS
Boolean variables are usually named to reflect their true state. E.g. the variable 'isComplete' would be initialised to have a value of 'true' if the thing really is complete. The variable name and the value should make sense.
SOME TERMS
Immutable: a String is immutable. This means that it cannot be modified. Unlike an int.
So, simply adding a method to a String variable will not do anything since the String variable cannot actually be changed. To solve this, any modification attempt of a String should assigned to a variable. Often the variable can be the same as before.
SOME SYNTAX
'
boolean add(E o)
' is used in documentation to indicate what elements can be added to an ArrayList. In this case, elements of type 'E' can be added. Real example: boolean add(String o) means elements of type String can be added.
E get(int index) is used in documentation to indicate which type of elements can be returned from an ArrayList. In this case 'E' elements can be returned. REal example: String get(int index) means that String will be returned.
Import Statements:
'import package-name.class-name' Real example: java.util.Random. In this example, java.util is the package name. Putting a '*' instead of a class-name will import all classes from that package.
CH6
:
More Sophisticated Behaviour:
How to work with library classes
A good Java programmer should know some of the most important class, and be able to find out/look up other classes.
The Java documentation show the
interface
of all the classes. I.e. how each class works. It doesn't show the code for each class since, if the interface is well written, knowing the code doesn't matter.
The source code underpinning each class is know as the
implementation
, as opposed to the
interface
.
Random Class
Java cant actually produce real random numbers because algorithms are needed to and since they're human made, they just can't do it. So we say that the Random class produce pseudo-random numbers.
Conditional Operator
Can be used instead of an 'if' statement. Works like this:
somevariable = otherVariable == 10 ? "Child" : "Adult";
There are 2 characters '?' and ':' and 3 operands. The last 2 operands must be expressions, they cannot contain methods.
HashMap
A map is a set of key/value pairings. Each key and value is an object. There is no index with a map, instead the key object acts in this way.
A
hashmap
is a form of a map. It has important 'get' and 'put' methods.
Creating a new hashmap includes stating what data type each key and value is.
E.g. HashMap <String, String> contacts = new HashMap<>().
its easy to look up the keys, but its difficult to look up from the value side.
Lists vs Sets
A set does not allow duplicates, does not keep insertion order.
A list allows duplicates and keeps insertion order.
They are quite similar.
keySet
A method that is used on a map that returns a set. E.g. executing this on a hashmap will return a set containing all the keys.
Autoboxing
primitive types need to be converted to objects before they can be inserted into list. So this process is called
boxing
, and the reverse is called
unboxing
. Java does this automatically, hence 'autoboxing.
This is achieved with the
Wrapper
class.
Note: dont say for example ArrayList<Int>, rather say ArraList<Integer>. Each primitive type has its own wrapper class.
Public vs Private
These keyword are modifiers and control the visibility of fields, constructors, methods, or classes.
fields are usually private because they only need to apply to what is near them, like a method.
Methods are usually public, because they provide a way for a class to perform some action, so they need to be accessible from outside the class it belongs to.
Helper methods
are different. They are usually private because they are only needed to perform actions within the class they belong to.
The
interface of a class
shows a programmer what they need to know in order to use the class effectively. Hence, private fields or methods are private and not shown on the interface because a programmer does not need to know about them.
The
implementation
part of a class is the part of a class that shows the details of the methods, constructors, fields, etc that run the class. This part of a class is aka the private part of a class.
Static
Keyword
This keyword defines class variables. As opposed to instance variables.
These are variables that are stored in the class itself. not in an object. Hence, they are not declared in the constructor.
All object instances share class variables.
Constants
These are variables that remain the same for all instances and cannot be changed.
These include the keyword,
final
, before the type name.
And they must be initialised with a value at the point of declaration.
private final int SIZE = 10;
note: var name is capitalised to differentiate it from other variables.
Note: there is no 'static' keyword here.
Variable SUMMARY
:
with static -> class variable, instances do not get a copy of the var and can only use the var assigned on declaration within the instance.
with static and final -> instances do not get a copy of the var and must use the value declared initially.
Static can be used for methods too.
These methods can be invoked without there being an instance.
These methods can only access class variables. Not variables of instances.
They also may not call an instance method from the class.
Sorted Collections
There is
TreeSet
and
TreeMap
which are classes that sort collections according to their values.
These classes automatically sort the items that they contain. So if you want a list of things that are sorted, its better to use these over the normal HashSet or HashMap.
CH3
: Object Interaction
ABSTRACTION
: the ability to focus on general broad ideas instead of the details.
Used to deal with the
complexity
that some programs will generate.
Divide and Conquer
: divide problem into sub-problems, then again and again until a single problem is easy to deal with.
Once one problem is solved, then we don't need to think about it anymore. It becomes a building block of the whole program.
This is
MODULARIZATION
OBJECT DIAGRAMS
static
view: shows classes (aka class diagram)
dynamic
view: shows objects at runtime.
TYPES
PRIMITIVE
predefined by java, include int, boolean, etc
stored in a variable
OBJECT
defined by classes
not stored in variable, instead reference to object is stored.
OPERATOR
De Morgan's Laws
In Java we can say that the following conditions are equivalent
! (A || B) is the same as ! A && ! B
! (A && B) is the same as ! A || ! B
+
- concatenation
Using this with a string then a number will convert the number to a string.
Using with 2 numbers will result in the numbers being added.
INCREMENT
new
This is used when creating an object
new ClassName (parameter-list)
This creates an object of the named class.
Executes the constructor of that class.
Assigning this to a variable creates a reference to that object from a different class.
E.g. if a class has in its constructor this statement: hours = new NumberDisplay(24);
This creates an object, and a reference to that object so that when we want to deal with that object, we can use 'hours' to do so.
Its possible for a class to have more than one constructor. This is called
overloading
.
A
zero-argument
constructor is one without parameters.
METHOD CALLS
Internal method call
When method call and method code are in same class.
Hence, no 'variable.method()' syntax. Just 'method()'.
You can use "self.methodName" where self means this object. Or you can just name the method directly without "self"
External method call
A method call to a method of another object
'object.methodname()'
this
parameters and variables can have the same name.
public MailItem(String from, String to, String message)
{
this.from = from;
this.to = to;
this.message = message;
}
Why can't I write from = from?
If I do, then the parameter 'from' will be used because it is the closest enclosing block to where it is being used.
Writing 'this' signifies that the 'from' field from the object that is using it will be used. So it negates the use of the parameter 'from'. So we can use 'this' to use the field instead of the parameter.
So:
field named
from =
parameter named
from;
We do this for readability reasons. We could just use different parameter names. But that would make reading the code more difficult.
Some names are just perfect.
Chapter 11: More about inheritance
Method polymorphism
Version of method in subclass overrides the version of the method in the superclass.
The superclass does not know about the stuff in its subclass.
The superclass cannot use the fields in its subclasses.
Static vs Dynamic Types
Problem is that the variable can have a type, and the object that is stored in the variable could be of different types.
Static
: the declared type of the variable.
This is declared in the source code, before runtime, so is a static representation of the program.
Maybe it happens that an object calls a method that does not exist in its class.
This was not an issue before, because it was always the variable type matching the thing it stores. E.g. int num = 5;. The variable 'num' is of type int, and the value '5' is clearly an int.
Dynamic
: the type of the object stored in the variable.
The assignment is completed at runtime, so the type could depend on the behaviour of the program.
Maybe it happens that an object calls a method that belongs to its class at runtime only. Such is the case when an object obtains the characteristics of the subclass only at runtime, but at compile time, such characteristics do not exist.
The issue is that at compile time, the compiler checks to see if the static types have the methods that are being called in their class. If the class does not have the method that is being called, then it won't compile. This is despite object that is calling the method will be a subtype of the supertype at runtime.
Overriding
(aka redefinition)
A method is defined in a superclass, like the display method in Post (see network-v3) and there is a method in the subclasses with the same signature.
Override
may be written before the method in the subclass to override the method in the superclass.
Hence, object of the subclass will have 2 methods with the same signature.
method lookup/method binding/method dispatch
Suppose simple class with display() method and an object of the class stored in a subClass variable 'var'
subClass var = new subClass
Method lookup proces (simple):
execute var.display();
var is accessed.
object stored in 'var' is found.
class of object is found.
the display() method is found in the class.
Suppose a simple subclass with no methods but there is an object of the subclass stored in a subClass variable 'var'. The superclass has a display() method.
subClass var = new subClass
Method lookup proces (with inheritance):
execute var.display();
var is accessed.
object stored in 'var' is found.
class of object is found.
no display() method is found in the subclass.
So, the method is searched for in the superclass.
if no method in superclass, then next superclass is searched and so on until the Object class is searched.
Since display() is in the superclass, it is found there and is executed.
Suppose a simple subclass with no methods. There is an object of the subclass (not the subclass this time) stored in a SuperClass variable 'var'. The superclass has a display() method. And the subclass has a display() method too with the
Override
statement before it.
superClass var = new subClass
Method lookup process (with inheritance and polymorphism):
execute var.display();
var is accessed.
object stored in 'var' is found.
class of object is found, and it is found to be of the subclass, because at runtime, since the object was statically defined as a superclass type, at runtime the object is actually of the subclass - at runtime.
a display() method with an override statement is found in the subclass.
So, that method is executed.
At runtime, the object is seen as the subclass, but at compile time, the object, because it is stored in a superClass variable, is seen as a superclass.
Notes:
General rules are applied whether there is a discrepancy between the variable type or the object type of the object that is stored in the variable.
The method that is used is determined by the dynamic type, not the static type.
Override
methods take precedence.
The lowest method in the heirarchy is used (if Override is used). If no override, then the superclass method is used.
To use both methods, one can use the normal var.display(), but then also include super.display() within the subclasses display() method to use the display() method in the superclass.
Point 5 is a form of
method polymorphism
(aka: polymorphic method dispatch).
Remember, a polymorphic variable is one that can store objects of varying types. Method calls can be polymorphic too because their calls could refer to methods in different classes.
The OBJECT class
toString
Returns a string representation of an object - the name of the class of which the object is an instance of, and a memory address of there the object is stored.
Classes can override the toString method by defining the a method with the same name, i.e, public String toString().
Because the Object class is a superclass of all objects, it means that all objects in any class has access to the toString method. So, this solves a problem. The problem being that if you want a method in a superclass to have access to fields in subclasses, you cant just put a custom method in the superclass. But you can override the toString method that is placed in the subclass. The subclass then calls the overriden toString method...
equals and hashcode
reference equality
vs
content equality
Reference equality is when an object variable is assigned to another variable using '=='. E.g. both var1 and var2 refer to the same object. It just looks at whether the variables assigned are the same and does not look at if the object contents are the same.
Content quality is a test to see if the contents of the objects are the same internally.
We can use the '
equals
' method (inherited from the Object class) to test for this. It checks if the objects state is the same as another. E.g.
var1.equals(var2).
But note that the method in Object only checks for reference equality.
To test if 2 objects are the same internally, one has to look at whether their fields are the same. One can override the equals method of the object class to do so. See online for info on how to do this.
The hashCode method returns an integer value that represents an object. It should be used in conjunction with the equals method to find out if content equality exists between 2 objects or not.
When overidding the hashcode method and the equals method, and if doing an equality test between two objects, they should both return the same hashcode value.
If the hashcodes are different, then problems ahead could be encountered if this is not done since 2 objects, even if they have the same content (i.e. content equality), their hashcodes are still naturally different, so they must be made equal.
header to override hashcode is 'public int hashCode()
To check content equality, the hashcode should be run on the fields of the objects. If done like this, then the value returned, if each object's fields are the same, will be the same too.
Connection to hashtables.
1 more item...
A nice method to use to include in an overridden hashcode method is the hash method
It allows you to insert parameters that represent fields you want to test for equality. So an overridden hashcode method could look like this:
public int hashCode()
{
return Object.hash(author, timestamp);
}
This method will return the same value if the author and timestamp fields have the same values.
Protected access
: this lies between private public access rules. It allows subclasses of a superclass to access the method. This would not be possible if a method has 'private' set.
This is often used for methods and constructors, not for fields because that might weaken encapsulation.
Instanceof
: checks if an object is of a given class or not, allowing one to distinguish between objects that are instances of different subclasses, but which have the same superclass.
obl instanceof MyClass
This returns true if the dynamic type of obj is MyClass or any subclass of MyClass.
'obj' is a reference to an object and 'MyClass' is a reference to a class.
E.g. post instanceof MessagePost
CH2
: Understanding Class Definitions
Classes contain:
definitions of fields
constructors
methods
CLASSES
A class has 2 main parts:
Outer wrapping - 'class header'
Inner part - 'body'
Body
CLASSES
contain fields, constructors and methods
FILEDS
store data
another name for field = instance variable
usually start with 'private'
include a data type
include a user chosen name
end with semicolon
Fields are defined outside of methods.
They persist through the life of the whole object.
Are accessible to all of the object's methods.
If a field's value cannot be changed once initialized, we say it is
immutable
.
CONSTRUCTORS
construct the object. Otherwise known as initialisation.
after an object is constructed, it is no longer used.
The constructor initialises the fields, hence the fields and constructor have a close relationship.
Constructor's name always matches the name of its class.
A constructor never contains a return statement.
METHODS
implement behaviour of the object
Contain header and body
Method
HEADER
:
method headers have return type. constructors do not have return types
method wrapper includes the header + the part with the round brackets.
method header must have a return type or indicate 'void' to show nothing will be returned.
Method
BODY
contain declarations and statements that define what an object does
4 more items...
ACCESSOR
methods
return information to the caller about the state of the object.
usually contain a return statement.
aka
GETTER
these methods often prefixed with 'get'
MUTATOR
methods
methods that change the state of the object via certain operations.
aka
SETTER
these methods often prefixed with 'set'
Common method is println(). Which is a method of the 'System.out object that is built into Java.
Class header
Often contain the words 'public' and 'class'. These are called key words or reserved words. There are 50 of these in Java.
Java key words never contain capital letters.
provides the name for the class. Usually starting with an uppercase letter.
PARAMETERS
defined in the header of a constructor or method.
makes data from outside the constructor or method available inside.
formal parameters
= the name given to a parameter
if multiple parameters, then separate with a comma.
actual parameters
= the actual value assigned to the formal parameter.
Is only available within the body of a constructor or method. The scope is restricted.
the scope of a field, however, covers the whole class.
The
lifetime
of a parameter is limited to a single call of a constructor or method.
ASSIGNMENT
: copying a short-lived value stored in a parameter into a more permanent variable.
assignment is usually done in the body near the beginning with an assignment statement.
the data type of the parameter must match the data type of the variable it is assigned to.
CONDITIONAL STATEMENT
aka = if statements
if (test) {
do something
}
else {
do something else
}
the 'test' part is a boolean expression which usually has an '
operator
'
the context can affect an operand. E.g. in concatenation, the '+' symbol might convert an int variable to a string. Operands that are altered by their context are called '
overloaded
' operators.
unary
operators have only one operand. E.g. '++'
binary
operators have 2 operands.
the 'else' part is not necessary to compile the code.
3 kinds of
VARIABLES
Fields
fields defined outside constructors and methods
store data that persists throughout the life of an object.
have class scope
means that methods can change the values of these.
if defined with 'private', fields cannot be accessed outside the class in which they are defined.
structure:
public/private type name
parameters
persist only for the period that a constructor or method executes.
defined in the header of a constructor or method
local variables
persist only for the period that a constructor or method executes.
defined inside the body of a constructor or method
must be initialised before they are used in an expression.
not accessible from anywhere outside the block in which they are defined.
Ch5
: Functional processing of Collections
Processing data starts with a data source and ends with a method that collects the results.
Java was at first an
imperative
language. but then was modified to have
functional
qualities as well.
Lambdas
and
streams
(closures) were added.
LAMBDAS
A segment of code that can be stored and used later.
The segment of code could be a parameter, and could be passed to a method.
Structure when lambdas are applied to collections:
collection.doThisForEachElement(some code);
Syntax
Similar to a method, but does not belong to a class.
(parameter) ->
{
Something to do;
}
Note that no private/public keyword, nor is a return type required. These are inferred from the context.
Basically, it works like...parameter...do something to the parameter
Used for once-off tasks.
Know as
anonymous
functions
The predicate: takes at least 1 argument and returns a boolean.
STREAMS
Similar to collections, but...
Elements accessed sequentially, not by index.
Content and ordering cant be changed.
Could be infinite.
functions
filter function
filters out an existing stream by some conditions and produces a new filtered stream.
intermediate operation and outputs a new stream.
This filter operation is a method that takes a lambda as a parameter (called a predicate).
The lambda returns a boolean result. One that represents whether the list item matches or not the filter condition.
E.g. 1
aList.stream().filter(s -> "aCondition".equals(s.aMethod()))
E.g. 2
{
sightings.stream()
.filter(s –> animal.equals(s.getAnimal()))
.forEach(s –> System.out.println(s.getDetails()));
}
First creates a stream, filters it based on the given parameter which results in a new stream. The new stream is then run through a forEach loop that gets the details of each item in the loop.
map function
maps each element of a stream to new, different elements. A new stream of the new, mapped elements is created.
reduce function
collapses all elements in a stream into a single result.
It is a terminal operation.
Takes 2 parameters
The first one is called an identity, and it is like a counter of a running total.
The second parameter is a lambda. with 2 parameters. One for the running total and one for the current element of the stream.
E.g
sightings.stream()
.reduce(0, (total, count) -> return total + count);
Pipelines
chaining of 2 or more functions.
Always start with a source stream, followed by sequence of operations.
2 kinds of operations - (1)
intermediate
(all operations before the terminal one) and (2)
terminal
(last operation).
intermediate operations always produce a new stream.
terminal operations always produce a result, or are void.
Chapter 7: Fixed-size Collections
-UNFINISHED MATERIAL
This chapter is about
arrays
, with a small 'a'. These are different to ArrayLists, which are a specific java class. Main different I think is that arrays must have a fixed size.
Main advantages:
Fetching info form an array is quite efficient.
Arrays can store either primitive data-types or Objects. ArrayLists for example can only store objects. Note: that an int needs to be autoboxed in order to go into an ArrayList.
array variables
Declaring an array variable.
private int[] hourCounts;
The square brackets is the main feature that create a variable of type integer array.
int is called the
base type
of this array.
After declaration, you need to create an array object.
hourCounts = new int[24];
General form:
new type[integer-expression]
type is about the type of items to store.
integer-expression specifies size of array.
Using arrays
Get value by index: hourCounts[3] refers to the forth item in the array.
Set value in array by simply:
hourCounts[3] = 45;
This set the value of the forth item in the array to the int 45.
for loop
useful for when:
we want to execute some statements a fixed number of times.
we need a variable whose value changes a fixed number of times by a fixed amount.
Its good for situations that require
definite iteration
.
Its actually close to a while loop than a for each loop.
Which loop to use?
You know how many iterations
for loop
You dont know how many iterations
while loop
you're dealing with a collection
for each
You need to remove items from a collection
for loop + iterator.
Two-dimensional Arrays (NOT ASSESSED)
Basically, an array where each element is itself a one dimensional array.
Declare:
int[][] myArray = new int[3][5];
convention: first array[3] are the rows, the second array[5] are the columns.
Initialise:
int[][] myArray = {{4, 3, 1, 5, 3}, {9, 5, 3, 8, 2}, {4, 2, 9, 4, 3}};
each curly '{' is a row.
To access, do like this:
myArray[2][3]. This will access row index 2, col index 3.
If you go myArray[0], then you will access the entire first row.
.length will give the number of rows.
myArray.length
to get the col length, you go:
myArray[0].length. The number of cols in first row.
To loop over either the rows or the cols, you need to fix one of them, then loop over the other.
Like this:
for (int i = 0; i < myArray[0].length; i++){System.out.print(myArray[2][i]);}
This will iterate over each col in row index 2.
A neater way is like this:
for (int aRowElement : myArray[2]){System.out.print(aRowElement);}
To print each element in a col, we can do like this
for(int i =0; i < myArray.length; i++){System.out.print(myArray[i][4]);}
Chapter 10: Inheritance
Superclass
: a class that overlaps functionality between different classes, lessening duplication.
Object Inititialisation
You have to connect classes to this superclass. One can call those, subclasses. They are classes that will use the resources within the superclass. You do this by adding "extends [superclassName]" to the subclass header of the subclass.
Takes place when a constructor is called with the keyword 'new'
Memory allocated.
Object's field given values of zero.
Constructor called (sometimes 'this' is used - see below).
Parent class constructor is called - i.e. 'super'
fields like constants, that are outside the constructor are initialised.
Code in constructor is executed.
To use fields that are in a superclass, they should be given the public. But if you do that, then the fields will be open to all. So instead one should use a public method, like get[varName], that is in the superclass to get the fields within.
To call such a method, it is no different to writing 'methodName()'. Its no different to normal.
Empty arrow from subclass to superclass indicates this relationship, i.e. subclass->superclass relationship.
'
super()
'
This is a call from the subclass to the superclass' constructor.
Its a way to access the superclass' methods
It can be used to access the superclass' fields.
Suppose 'super' is used in the subclass' constructor. Further suppose the subclass constructor has a parameter - String name. When creating the subclass object, you will be required to enter a name. The name you enter goes into the constructor, goes to super(name). Assume the superclass name a String name parameter in its constructor. So the name you enter will go from the subclass to the superclass constructor.
E.g.
super(name) - in subclass.
name goes into superclass constructor as a parameter.
Then in the superclass constructor, you might find something like username = name.
And so the username field will be assigned to name.
Each subclass gets its own copy of the username field. So username is not set for the superclass, only the object that is created from it.
it is always called when there is a subclass superclass relationship. It will either be called implicitly by the superclass, or explicitly in the subclass by using 'super(something something)' in the subclass constructor. It should always be the first field in the subclass constructor.
Construction of an instance
If supercalss, then fields common to all subclasses need to be initialised. You could do it by making a mutator method in the superclass, and then having the subclass use that method, but that leaves the field in a position where is could be changed.
Instead, the superclass constructor should take the field as a parameter and initialise it when it is constructed. It gets called when a subclass is constructed. The subclass will have the same parameter as the superclass. So creating a constructor will force the use of a parameter. That parameter will get passed to the superclass and get initialised via the 'super' syntax. The subclass, the instance created in this way, will then obtain the initialised field in this way.
Whatever other fields that might be in the superclass constructor will also be passed to the instance.
It seems like the subclass is a kind of constructor of the superclass. A special kind that only allows certain fields or values to be used from the superclass.
The subclass must use the superclass's constructor as its first action and it should use 'super' plus any parameters that are needed. If no 'super' is used, Java automatically makes a 'noarg' call to 'super()' behind the scenes.
Its like the subclass is a filter for the super class. It filters out the fields it does not need, and keeps the ones that it does need.
What if we don't want to inherit all the fields in the superclass?
Cant just ignore the fields, because someone who doesnt know about that might end up using them.
Cant just make another class, because thats duplication.
Answer
: Refactor superclass to have another sub-superclass that the subclass will rely on. So, there is a superclass, which has subclass that is also a superclass to another subclass -
3 levels
.
The class in between is called an
abstract class
.
All object that have not been given a superclass, have 'Object' as their superclass.
Hence, polymorphic variables of type object can hold any object.
The object class's methods can be available for every existing object.
The object class already has a number of important methods.
We can use 'this' to call a constructor from another constructor. 'this(param1,param2)' when inserted as the first line of a constructor, will apply the line to the 2 arg constructor (which must exist).
Subtypes
and
supertypes
This is referring to the idea that the objects of subclasses are subtypes of the superclass, or the supertype.
Subtyping and assignment: we can assign objects to variables that are types of the supertype.
E.g. Car myCar = new Car();
Object of type car is assigned to variable that holds Car objects.
But, lets go further. An object can hold objects not only of its declared type, but also of subtypes of the declared type.
supertype = new subtype is okay.
subtype = new supertype is not okay.
Polymorphism
Means that a variable that can reference many shapes
Often are objects (that is, variables that reference objects), and it seems that are superclasses.
E.g. an object variable that is a superclass. All subclasses are able to be referenced by that variable. Hence, its polymorphic.
Casting
Suppose: vehicle = car, then we try: car = vehicle. It wont work.
We cant do it because the compiler translates code line by line, no memory. We think, ah a car is a vehicle, a vehicle holds car objects. But compiler doesnt see that. The compiler doesnt recognise that, it lost the Type of the vehicle object - this is
type loss
.
Extra note
: variable assignment. This:
v = c can be read as 'assign a car to a vehicle.' The right is assigned to the left side.
But, there is a way around if we go car = (Car) vehicle. The (Car) part is a
cast operator
.
It makes the compiler think 'vehicle' is a car. And if it really is, the compilation will complete. If its not really a car, then at runtime, a
ClassCastException
error will occur and program will stop.
Type loss is misleading
because the type has not been lost, its just that only at runtime are objects made, so the compiler just cant see what it is yet. So casting is a way to tell the compiler, 'hey, this variable is of XYZ type.'
Casting is rarely used
because it is not certain. It is not certain that an object will really be what the coder plans it to be. Casting seems like a workaround, a hack of some sort.
PREQUEL
Fundamental Hardware and Software
Source code is translated to machine code
Programming code is high level
Machine code is low level
Compiler translates source code to machine code.
COMPILE
Interpreter also does this, but a line of source code at a time when it is required.
Compiler first checks if source code conforms to syntax rules of the language. If check is successful, then it is turned into machine code.
Different computers use different compilers, so sometimes its not simple to run software on different computers.
So virtual machines (VMs) help with this. It resides on top of an OS.
Here, the source code is translated into intermediate code which is the code of the VM instead of into hardware dependent machine code.
This code is called bytecode, not machine code.
It allows code to be used on different hardware.
3 Options from bytecode
Include an interpreter in the VM which translate source code into machine code specific to the hardware being used.
Static compilation: VM translates all intermediate code into machine code in one go. Traditional approach.
Just in time compilation (JIT): Used by Java VM. It both compiles and interprets. The VM translates intermediate code into machine code, which is then stored. Subsequent source code is then interpreted.
Computer is a layered device.
Bottom to top:
Hardware.
OS
Software and JVM + Java Programs
Object Technology
Procedural programming: step-by-step.
Has a main program that contains further, smaller programs like functions.
Problem can be that this method relies on data structures, which if changed, could result in a need to change all the functions of the entire program.
Object-oriented programming (OOP)
Instead of procedural approach, do OOP. Maps the real world by creating objects that interact with each other. (How these cant be considered as functions is not clear to me).
It seems that in answer to my question in brackets in previous bubble, software components, which are reusable pieces of software, include data in their make-up. And if they are termed as objects, then having the data paired with the object would make it seem quite different from the procedural approach.
JAVA
Java Development Kit (JDK), Private. Will be used in this module.
Java Runtime Environment (JRE). Public
Chapter 9: Debugging
Compile-time errors
: errors that cause compilation to fail.
Aka
static errors
. These errors can only be identified without the program running.
Unreachable error
: when a statement lies beyond a return statement
Runtime errors
: errors that occur after the program is compiled and is running.
logical errors
fall in this category. The program is not logical for some reasons and when running, leads to an error.
aka bugs
Do
testing
to deal with logical errors.
Design by contract
means that the coder is at fault if the code is used incorrectly. If you obey the 'code' then it will perform as expected.
Defensive code
: write code in such a way that it shows you if errors in logic are around.
Some ways to test:
Document when code is not expected to work.
2.
Positive testing
: test will known, correct outputs.
Test with values that should not work, aka
negative testing
.
Boundary testing
: test with values near the boundaries of what might lead to correct or incorrect output. Linked to '
off-by-one
' error, where the code logic calculates the output by one 'thing' being off. x < 0, or x <= 0.
Regression errors.
These could occur when new feature is added to already existing code, which generates outputs that have not been tested for. Hence, the new outputs dont 'gel' with the older code and causes errors.
Exceptions
: errors that occur at runtime.
Exceptions are objects that are created by an exception class.
Common exceptions:
ArrayIndexOutOfBoundsException
- program tries to access an array with an index outside the array's limits.
ArithmeticException
: like dividing by zero. Math error.
NullPointerException
: try to call method when reference var is null.
NumberFormatException
: when stong to int converter method gets an arg with wrong format.
StringIndexOutOfBounds
: when try to access the part of a string that is out of its bounds.
StackOverFlowError
: when so many methods are called that the stack space has become full.
These are classes.
Debugging Principles
Check documentation
Wrint one thing, fix one thing.
Use skeleton code and wrappers.I.e. Test with dummy variables first. Progress step by step.
Read every character of your code.
Be persistent, take breaks.
Explain your code to yourself.
Draw a picture/sketch diagrams.
Use tools.
Keep backups.
Ask in forums.
Ch4
: Grouping Objects
COLLECTIONS
A collection is a bunch of objects grouped together. OR
A data structure that allows us to store references to multiple objects and perform operations with them.
Like a group of students, the course one student is taking, etc.
Operations can be done to the collection, like sorting in some way, reducing it, etc.
Its kind of like a class itself.
Which can have instances, and those can have objects.
And there are libraries of these in java.
In java these are called packages
Packages contain a number of classes that are useful to programmer, like the
ArrayList
class from the
java.util
package.
1 more item...
LOOPS
Aka:
iterative control structures
.
for-each loop
for (
ElementType element : collection
) {
loop body
}
pseudo-code
:
for each
element
in
collection
do: {
loop body
}
E.g.
for (String filename : files) {
System.out.println(filename);
}
You can see that the "String filename" part is a declaration of a new variable that is then used in the loop body. Its the counter.
This counter is called the
loop variable
.
The variable can be named anything we want, but its type should match the type that is in the collection.
Used to process whole collections.
Could be called a
definite iteration
(it has a start and end point).
while loop
Aka:
indefinite iteration
while(
boolean condition
) {
loop body
}
pseudo-code
:
while (whatever is true) do: {
loop body
}
More complex to code than a for each loop because you have to make your own counter, and each element in a list needs to be extracted.
possible to write an infinite loop.
Benefits: (1) does not need to run on a collection. (2) does not need to process every item in a collection.
Used to
search
for things in collections and elsewhere.
What if you do not find what you want? Then you need a way to end the loop or it will become an infinite loop.
the boolean condition part of the loop and using an index can limit the number of iterations and bring the loop to an end.
Two ways to end a search. (1) finding the thing you are looking for. (2) The thing you are looking for is not there. There needs to be a way to alter the while boolean condition if either of those results are encountered.
Iterator
There is the Iterator class/interface, and there is the iterator (small 'i') method that belongs to the ArrayList class.
Using the iterator method on ArrayList will produce an Iterator object that has 4 methods, 2 of which are hasNext() and next(), both of which have non-void return types.
pseudo-code
:
[FIRST, create the Iterator object]
Iterator<
ElementType
> it = myCollection.iterator();
[THEN, use a while loop to use it]
while(it.hasNext()) {
call
it.next()
to get the next element
do something with that element
}
indefinite
method of iteration
Possible to remove items in the collection with this method. Only the last item retrieved from the Iterator's next method can be removed.
It is a
generic type
.
All collections provide the iterator method
CH1
: Objects and Classes
CLASSES
: the blueprints of objects
OBJECTS
: an example of a particular class
have data fields, the value of the data tells us the objects
state
.
Otherwise known as
PARAMETERS
.
can have their own unique characteristics
Instance is used interchangeably with objects sometimes.
An object has
fields
, that are determined by the class of an object. These give the object characteristics. Every field has a certain value.
Each object has a copy of the characteristics of the class, but may vary in terms of what each characteristic is. E.g. characteristic = colour, specific = 'red'.
The values that each field has sets the state of an object. To change the state, we can't just change the object. Instead, we should 'ask' the object to change so and so characteristic by invoking a method.
Objects do 'operations' which are 'actions' that an object can do.
Operations are implemented using '
METHODS
'
The nomenclature is to say 'invoke a method' or 'call a method'
Some methods require additional values called
PARAMETERS
.
There can be many parameters.
All the values of all the parameters set an object's '
STATE
'.
Another way to say is "objects have
ATTRIBUTES
that are stored in fields which set an objects state."
Objects of the same class have the same set of attributes, but the values of each might be different. These are defined by the class.
Other objects can be used as parameters for methods of other objects.
Method Structure:
header eg: void moveHorizontal (int distance)
ínt distance' is a parameter
ínt' is the
data type
of parameter. 'distance' is the name of the parameter.
'void' means that nothing is returned. If something like 'String' is there in place of 'void' then it means that a value of string data type will be returned by the method.
Objects of the same class have the same set of methods.
Methods can change an objects state, or return values that represent its current state.
Each object made from a class are independent after being made.
Objects can create other objects
labelled by capitalising the first letter.
A class should represent a distinct kind of object.
This means that one program could have multiple classes, and therefore multiple objects.
Chapter 8: Code Conventions and Design
Use as a reference
Chapter 12
: Further Abstraction Techniques
Abstract classes
Cant be instantiated. I.e. there can be no instances of them.
Methods
Abstract methods
don't have bodies, only signatures.
Implement abstract method in abstract class without body, if you do, then you have to implement the same method in the subclass concretely. And every subclass that extends the superclass (i.e. the abstract class in this case) must have such a method. And it must have the Override statement.
Can have concrete methods with bodies.
Using
Override
in the subclasses is optional but recommended.
Abstract methods are used to enforce a certain structure. An abstract method declared in a superclass forces all subclasses to use the method. It forces them to all have the same behaviour, at minumum.