Week 5 Lecture 05

Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

INFO1113 / COMP9003

Object-Oriented Programming

Lecture 5

The University of Sydney Page 1


Contents developed by Tyson Thomas
Acknowledgement of Country

I would like to acknowledge the Traditional Owners of Australia and recognise


their continuing connection to land, water and culture. I am currently on the land
of the Gadigal people of the Eora nation and pay my respects to their Elders,
past, present and emerging.

I further acknowledge the Traditional Owners of the country on which you are on
and pay respects to their Elders, past, present and future.

The University of Sydney Page 2


Always try to be in the green zone!

The University of Sydney Page 3


Copyright Warning

COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to you by or on behalf of the
University of Sydney pursuant to Part VB of the Copyright Act 1968 (the Act).

The material in this communication may be subject to copyright under the Act. Any
further copying or communication of this material by you may be the subject of
copyright protection under the Act.
Do not remove this notice.

The University of Sydney Page 4


Topics: Part A Superclass/
Animal Parent

● Inheritance basics
Subclass/
● Encapsulation Cat Dog
Child
● Programming Inheritance

● Modelling an is-a relationship and UML

The University of Sydney Page 5


Inheritance

Inheritance is a significant concept of OOP. Allowing reusability and


changes to inherited methods between different types in a hierarchy.

What does inheritance offer?

● Attribute and method reusability

● Defining sub-class methods

● Overriding inherited methods

● Type information

The University of Sydney Page 6


Inheritance

How does it work?


We will be introducing a new keyword today called extends, this
keyword allows the class to inherit from another class.

Syntax:
[public] class ClassName extends SuperClassName

The class we are inheriting


from. It will inherit any
protected or public
methods or attributes
Class definition, we ClassName (What you are We are inheriting from the
specify the access going to name the class) following class. It is seen
modifier as an extension of the
super class.

Refer to Chapter 8.1, page 624-629 (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 7


How it looks

Part of our class declaration line allows for us to define what class
we want to extend from

public class Dog extends Animal

Once defined, Dog type can also be used as a Animal type as it is


just an extension of such type.

Refer to Chapter 8.1, page 624-629 (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 8


Encapsulation

We have used the public and private access modifier but we will now
use the protected access modifier.

What does protected mean?

Like private it will not be accessible to other classes but now with the
exception inherited classes.

● Is only accessible within the class


● Attributes and methods will be accessible by all subclass

Refer to Chapter 8.1, page 632 (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 9


Inheritance

So let’s take a look how inheritance works between two classes.

public class GlassBottle extends Bottle {

public class Bottle {


protected String name;
protected double width;
protected String name;
protected double height;
protected double width;
protected double depth;
protected double height;
protected double litresFilled;
protected double depth;
private boolean shattered = false;
protected double litresFilled;

public void shatter() {


System.out.println(“We lost “ + litresFilled + “Litres”);
public double volume() {
litresFilled = 0;
return height*width*depth;
shattered = true;
}
}

}
public boolean isBroken() {
return shattered;
}
}

The University of Sydney Page 10


Inheritance

So let’s take a look how inheritance works between two classes.

public class GlassBottle extends Bottle {

public class Bottle {


protected String name;
protected double width;
protected String name;
protected double height;
protected double width;
protected double depth;
protected double height;
protected double litresFilled;
protected double depth;
private boolean shattered = false;
protected double litresFilled;

public void shatter() {


System.out.println(“We lost “ + litresFilled + “Litres”);
public double volume() {
litresFilled = 0;
return height*width*depth;
shattered = true;
}
}

}
public boolean isBroken() {
Subclass will have access return shattered;
to any protected and }
public methods.
}

The University of Sydney Page 11


Inheritance

So let’s take a look how inheritance works between two classes.

public class GlassBottle extends Bottle {

public class Bottle { Protected like private but


allows subclass to inherit protected String name;
the property. protected double width;
protected String name;
protected double height;
protected double width;
protected double depth;
protected double height;
protected double litresFilled;
protected double depth;
private boolean shattered = false;
protected double litresFilled;

public void shatter() {


System.out.println(“We lost “ + litresFilled + “Litres”);
public double volume() {
litresFilled = 0;
return height*width*depth;
shattered = true;
}
}

}
public boolean isBroken() {
return shattered;
}
}

The University of Sydney Page 12


Inheritance

So let’s take a look how inheritance works between two classes.

public class GlassBottle extends Bottle {


All properties from the super
public class Bottle {
protected String name; class are inherited by the
protected double width; subclass. As if they were
protected String name; defined in the class itself.
protected double height;
protected double width;
protected double depth;
protected double height;
protected double litresFilled;
protected double depth;
private boolean shattered = false;
protected double litresFilled;

public void shatter() {


System.out.println(“We lost “ + litresFilled + “Litres”);
public double volume() {
litresFilled = 0;
return height*width*depth;
shattered = true;
}
}

}
public boolean isBroken() {
return shattered;
}
}

The University of Sydney Page 13


Inheritance

So let’s take a look how inheritance works between two classes.

public class GlassBottle extends Bottle {

public class Bottle {


protected String name;
protected double width;
protected String name; Able to refer to the attributes
protected double height;
protected double width; within the subtypes own
protected double depth;
protected double height; methods.
protected double litresFilled;
protected double depth;
private boolean shattered = false;
protected double litresFilled;

public void shatter() {


System.out.println(“We lost “ + litresFilled + “Litres”);
public double volume() {
litresFilled = 0;
return height*width*depth;
shattered = true;
}
}

}
public boolean isBroken() {
return shattered;
}
}

The University of Sydney Page 14


What about constructors?

The University of Sydney Page 15


Inheritance

Assuming the default constructor is given to the superclass, the subclass does
not need to define one.

public class Bottle { public class GlassBottle extends Bottle {

protected String name;


protected double width;
protected double height;
protected double depth; private boolean shattered = false;
protected double litresFilled;
public void shatter() {
public Bottle() { shattered = true;
}
}
public boolean isBroken() {
public double volume() { return shattered;
return height*width*depth; }
} }

The University of Sydney Page 16


Inheritance

Assuming the default constructor is given to the superclass, the subclass does
not need to define one.

public class Bottle { public class GlassBottle extends Bottle {

protected String name;


protected double width;
protected double height;
protected double depth; private boolean shattered = false;
protected double litresFilled;
public void shatter() {
public Bottle() { shattered = true;
}
By default,
} when a subclass object is created, it will refer to the super class’s constructor.
public boolean isBroken() {
public double volume() { return shattered;
public static void main(String[] args) {
return height*width*depth; }
} }
GlassBottle b = new GlassBottle();
System.out.println(b.isBroken());
}
System.out.println(b.name);
}

The University of Sydney Page 17


Inheritance

Assuming the default constructor is given to the superclass, the subclass does
not need to define one.

public class Bottle { public class GlassBottle extends Bottle {

protected String name;


protected double width;
protected double height;
protected double depth; private boolean shattered = false;
protected double litresFilled;
public void shatter() {
public Bottle() { shattered = true;
}
}
public boolean isBroken() {
public double volume() { return shattered;
return height*width*depth; }
} }

}
However! Nothing was initialised, so all we
get are default values

The University of Sydney Page 18


Inheritance

Assuming the default constructor is given to the superclass, the subclass does
not need to define one.
public class Bottle {
protected String name;
public class GlassBottle extends Bottle {
protected double width;
protected double height;
protected double depth;
protected double litresFilled;

private boolean shattered = false;


public Bottle() {
this.name = "Basic Bottle";
public void shatter() {
this.width = 10.0;
shattered = true;
this.height = 10.0;
}
this.depth = 10.0;
this.litresFilled = 0;
public boolean isBroken() {
}
return shattered;
}
}
public double volume() {
return height*width*depth;
}
Providing some values we can inspect the
} previous code segment

The University of Sydney Page 19


Inheritance

Assuming the default constructor is given to the superclass, the subclass does
not need to define one.
public class Bottle {
protected String name;
public class GlassBottle extends Bottle {
protected double width;
protected double height;
protected double depth;
protected double litresFilled;

private boolean shattered = false;


public Bottle() {
this.name = "Basic Bottle";
public void shatter() {
this.width = 10.0;
shattered = true;
this.height = 10.0;
}
this.depth = 10d.0
By default, when a subclass object is created, it will refer to the super class’s constructor.
this.litresFilled = 0;
public boolean isBroken() {
}
return shattered;
> java MyProgram
}
public static void main(String[] args) {
GlassBottle b = new GlassBottle();
public double volume() { false }
System.out.println(b.isBroken());
return height*width*depth; Basic Bottle
System.out.println(b.name);
}
}
} Providing some values we can inspect the <program end>
previous code segment

The University of Sydney Page 20


Inheritance

Assuming the default constructor is given to the superclass, the subclass does
not need to define one.
public class Bottle {
protected String name;
public class GlassBottle extends Bottle {
protected double width;
protected double height;
public GlassBottle() {
protected double depth;
this.name = "Glass Bottle";
protected double litresFilled;
}

public Bottle() {
private boolean shattered = false;
this.name = "Basic Bottle";
this.width = 10.0;
public void shatter() {
this.height = 10.0;
shattered = true;
this.depth = 10.0;
}
this.litresFilled = 0;
}
public boolean isBroken() {
return shattered;
}
public double volume() {
}
return height*width*depth;
}
What if we were to define a constructor in
} the subclass?

The University of Sydney Page 21


Inheritance

Assuming the default constructor is given to the superclass, the subclass does
not need to define one.
public class Bottle {
protected String name;
public class GlassBottle extends Bottle {
protected double width;
protected double height;
public GlassBottle() {
protected double depth;
this.name = "Glass Bottle";
protected double litresFilled;
}

public Bottle() {
private boolean shattered = false;
this.name = "Basic Bottle";
this.width = 10.0;
public void shatter() {
this.height = 10.0;
shattered = true;
this.depth = 10d;
By default, when a subclass object is created, it will} refer to the super class’s constructor.
this.litresFilled = 0;
}
public boolean isBroken() {
> java MyProgram
return shattered;
public static void main(String[] args) {
GlassBottle b = new GlassBottle();
public double volume() { 1000.0}
System.out.println(b.volume()); }
return height*width*depth; Glass Bottle
System.out.println(b.name);
}
}
} Providing some values we can inspect the <program end>
previous code segment
We can see that we called the GlassBottle constructor
The University of Sydney and it set the name to Glass Bottle. Page 22 22
Inheritance

Assuming the default constructor is given to the superclass, the subclass does
not need to define one.
public class Bottle {
protected String name;
public class GlassBottle extends Bottle {
protected double width;
protected double height;
public GlassBottle() {
protected double depth;
this.name = "Glass Bottle";
protected double litresFilled;
}

public Bottle() {
private boolean shattered = false;
this.name = "Basic Bottle";
this.width = 10.0;
public void shatter() {
this.height = 10.0;
shattered = true;
this.depth = 10d;
By default, when a subclass object is created, it will} refer to the super class’s constructor.
this.litresFilled = 0;
}
public boolean isBroken() {
> java MyProgram
return shattered;
public static void main(String[] args) {
GlassBottle b = new GlassBottle();
public double volume() { 1000.0}
System.out.println(b.volume()); }
return height*width*depth; Glass Bottle
System.out.println(b.name);
}
}
} Providing some values we can inspect the <program end>
previous code segment
Hang on! If we called GlassBottle() how is volume
The University of Sydney returning 1000.0? Page 23 23
Let’s try something

The University of Sydney Page 24


Inheritance

public class Bottle {


protected String name;
protected double width; public class GlassBottle extends Bottle {
protected double height;
protected double depth; public GlassBottle() {
protected double litresFilled; this.name = "Glass Bottle";
}
public Bottle(String name, double width,
double height, double depth) { private boolean shattered = false;
this.name = name;
this.width = width; public void shatter() {
this.height = height; shattered = true;
this.depth = depth; }
this.litresFilled = 0.0;
} public boolean isBroken() {
return shattered;
}
public double volume() { }
return height*width*depth;
}
}

The University of Sydney Page 25


Inheritance

public class Bottle {


protected String name;
protected double width; public class GlassBottle extends Bottle {
protected double height;
protected double depth; public GlassBottle() {
protected double litresFilled; this.name = "Glass Bottle";
}
public Bottle(String name, double width,
double height, double depth) { private boolean shattered = false;
this.name = name;
this.width = width; public void shatter() {
this.height = height; shattered = true;
this.depth = depth; }
this.litresFilled = 0.0;
} public boolean isBroken() {
return shattered;
}
public double volume() { }
return height*width*depth;
} What if we were to add a constructor with
} parameters?

The University of Sydney Page 26


Inheritance

public class Bottle {


protected String name;
protected double width; public class GlassBottle extends Bottle {
protected double height;
protected double depth; public GlassBottle() {
protected double litresFilled; this.name = "Glass Bottle";
}
public Bottle(String name, double width,
double height, double depth) { private boolean shattered = false;
this.name = name;
this.width = width; public void shatter() {
this.height = height; shattered = true;
The subclass must invoke the super constructor. Using
this.depth = depth; } the super keyword, we are able to refer
this.litresFilled = 0;
to inherited constructors and methods.
} > javac MyProgram.java
public boolean isBroken() {
public static void main(String[] args) { ./GlassBottle.java:5:
returnerror: constructor Bottle in class Bottle cannot be applied to given
shattered;
types; }
GlassBottle b = new GlassBottle();
public double volume() { public GlassBottle() {
System.out.println(b.volume()); }
^
return height*width*depth;
System.out.println(b.name);
required: String,double,double,double
} } What if we were to add a constructor with found: no arguments
} How would the GlassBottle constructor be
parameters? reason: actual and formal argument lists differ in length
able to invoke the super constructor?
The University of Sydney 1 error Page 27 27
Inheritance

public class Bottle {


protected String name;
protected double width; public class GlassBottle extends Bottle {
protected double height;
protected double depth; public GlassBottle() {
protected double litresFilled; super(“”, 0.0, 0.0, 0.0);
this.name = "Glass Bottle";
public Bottle(String name, double width,
double height, double depth) { }
this.name = name;
this.width = width; private boolean shattered = false;
this.height = height;
The subclass must invoke the super constructor. Using
this.depth = depth; public the super{ keyword, we are able to refer
void shatter()
this.litresFilled = 0;
to inherited constructors and methods. However... shattered = true;
} > javac MyProgram.java
}
public static void main(String[] args) { ./GlassBottle.java:5: error: constructor Bottle in class Bottle cannot be applied to given
We are able to use the super keyword to types; public boolean isBroken() {
GlassBottle b = new GlassBottle();
public invoke
double the parent
volume() { constructor. public GlassBottle() {
System.out.println(b.volume()); return shattered;
^
return height*width*depth;
System.out.println(b.name); }
required: String,double,double,double
} } }
What if we were to add a constructor with found: no arguments
} parameters? reason: actual and formal argument lists differ in length
The University of Sydney 1 error Page 28 28
Inheritance

public class Bottle {


protected String name;
protected double width; public class GlassBottle extends Bottle {
protected double height;
protected double depth; public GlassBottle() {
protected double litresFilled; Refers to Bottle constructor super(“”, 0.0, 0.0, 0.0);
this.name = "Glass Bottle";
public Bottle(String name, double width,
double height, double depth) { }
this.name = name;
this.width = width; private boolean shattered = false;
this.height = height;
The subclass must invoke the super constructor. Using
this.depth = depth; public the super{ keyword, we are able to refer
void shatter()
this.litresFilled = 0;
to inherited constructors and methods. However... shattered = true;
} > javac MyProgram.java
}
public static void main(String[] args) { ./GlassBottle.java:5: error: constructor Bottle in class Bottle cannot be applied to given
We are able to use the super keyword to types; public boolean isBroken() {
GlassBottle b = new GlassBottle();
public invoke
double the parent
volume() { constructor. public GlassBottle() {
System.out.println(b.volume()); return shattered;
^
return height*width*depth;
System.out.println(b.name); }
required: String,double,double,double
} } }
What if we were to add a constructor with found: no arguments
} parameters? reason: actual and formal argument lists differ in length
The University of Sydney 1 error Page 29 29
Inheritance

We could match the constructor of the


parent type.
public class Bottle {
protected String name;
protected double width; public class GlassBottle extends Bottle {
protected double height;
protected double depth; public GlassBottle(String name, double
protected double litresFilled; width,double height,double depth){
super(name, width, height, depth);
public Bottle(String name, double width,
double height, double depth) { }
this.name = name;
this.width = width; private boolean shattered = false;
this.height = height;
The subclass must invoke the super constructor. Using
this.depth = depth; public the super{ keyword, we are able to refer
void shatter()
this.litresFilled = 0;
to inherited constructors and methods. However... shattered = true;
} }
> javac MyProgram.java
public static void main(String[] args) {
./GlassBottle.java:5: error: constructor Bottle in class Bottle cannot be applied to given
GlassBottle b = new GlassBottle(); types;
public boolean isBroken() {
public double volume()
System.out.println(b.volume()); { publicreturn shattered;
GlassBottle() {
return height*width*depth;
System.out.println(b.name); } ^
} } What if we were to add a constructor with required:} String,double,double,double
} parameters? found: no arguments
reason: actual and formal argument lists differ in length
The University of Sydney
1 error
Page 30 30
Demonstration

The University of Sydney Page 31


Relationship

There are two types of relationships we will look at when it


comes to inheritance.

● Is-a relationship (Extension)

● Has-a relationship (Composition)

In regards to class inheritance we are considering the Is-a


relationship how a class is an extension of another class but is
also the other class.

The University of Sydney Page 32


Relationship

We have to be very certain with inheritance that any class that


inherits from another is a type of that class. There should be
clear reasoning that the types satisfy the relationship.

There needs to be clear reasoning to extending the super class.

Some instances where it makes sense:

● Super class is Cat and subclasses are Panther, Lion, Tiger

● Super class is Controller and subclasses are Gamepad,

Joystick, Powerglove
● Super class is Media and subclasses are DVD, Book, Image

The University of Sydney Page 33


UML Generalization

Let’s examine the following UML Diagram.

Protected is defined using the # symbol


and will be a variable that is inherited.

The University of Sydney Page 34


UML Generalization

Let’s examine the following UML Diagram.

When other classes inherit from the


superclass they will get the protected and
public fields

Refer to Chapter 8.1, page 635 (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 35


UML Generalization

Let’s examine the following UML Diagram.

When other classes inherit from the


superclass they will get the protected and
public fields

Generalization link, shows that GlassBottle


is a subclass of Bottle.

Refer to Chapter 8.1, page 635 (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 36


Super class and subclass

Some other factors to consider:

● Superclass does not know about its subclasses


● Subclasses cannot be constructed using a superclass constructor
Subclass a = new Superclass(); X
Superclass a = new Subclass();
● You cannot use subclass properties through a superclass binding.
● Private is not inherited, only protected and public
● Ensure when you use inheritance you are certain it will satisfy an is-a
relationship
● You can only inherit from 1 class.
● Within UML, inheritance is shown as a Generalization.

The University of Sydney Page 37


Let’s take a break!

The University of Sydney Page 38


Topics: Part B

● Method Overloading
● Constructor Overloading
● try-catch and exceptions

The University of Sydney Page 39


Overloading

Firstly! What is overloading?

In regards to Java we are able to use the same method name but
with different method signature.

Simply:

We are able to define a method such as add and have a version


that accepts two integers and another version that accepts three
integers.
When used, the
int add(int a, int b) parameters may be
different but java is able
Same name but both have to link to the correct
different parameters, method
therefore different int add(int a, int b, int c)
signature.

The University of Sydney Page 40


Where it is invalid

We are unable to apply overloading if we have a different return


type between the methods. The return type is not part of the
method signature.

For example:

float[] crossProduct(float[] a, float[] b)

int[] crossProduct(float[] a, float[] b)

Even though float[] and int[]


are specified here, the
compile cannot specify
which method it will call.

The University of Sydney Page 41


What about some ambiguous scenarios?

The University of Sydney Page 42


Ambiguous scenario

So let’s consider the following method calls using the two


methods and assume that they are correct.

int[] crossProduct(int[] a, int[] b)


int[] crossProduct(float[] a, float[] b)

Method calls: Which method could it be


calling?
int[] x = crossProduct(null, null);

int[] y = crossProduct(null, null); > javac OverloadTest.java


OverloadTest.java:15: error: reference to crossProduct is ambiguous
int[] o = crossProduct(null, null);
^
The compiler would be unable to determine exactly both method crossProduct(float[],float[]) in OverloadTest and method
what method is trying to be called and will throw an crossProduct(int[],int[]) in OverloadTest match
error. 1 error

The University of Sydney Page 43


Ambiguous scenario

So let’s consider the following method calls using the two


methods and assume that they are correct.

int[] crossProduct(int[] a, int[] b)


By casting the reference
int[] crossProduct(float[] a, float[] b) to a certain type, the
compiler can deduce what
method to call

Method calls:
int[] x = crossProduct((int[])null, (int[])null);

By casting float[] on the


int[] y = crossProduct((float[])null, (float[])null); null references we can see
it infer the method with
floats as arguments

The University of Sydney Page 44


So, let’s demo this!

The University of Sydney Page 45


Constructor Overloading

We can observe the same overloading concept applied to constructors.


This can be applied to both overloaded constructors within the same
class as well as super constructors.

We are able to also utilise certain constructors for other constructors if


we have already defined that behaviour.

The University of Sydney Page 46


Constructor Overloading
Let’s take a look at the following class
public class Person {

private static int DEFAULT_AGE = 21;

private String name;


private int age;

public Person() {
name = "Jeff";
age = DEFAULT_AGE;
}

public Person(String name) {


this.name = name;
this.age = DEFAULT_AGE;
}

public Person(String name, int age) {


this.name = name;
this.age = age;
}
}

The University of Sydney Page 47


Constructor Overloading
Let’s take a look at the following class
public class Person {

private static int DEFAULT_AGE = 21;

private String name;


private int age;

public Person() {
name = "Jeff";
age = DEFAULT_AGE;
}

public Person(String name) {


this.name = name;
We can see that there are
3 different constructors. this.age = DEFAULT_AGE;
Within our own code we }
choose to call anyone, in
fact we have already been
public Person(String name, int age) {
doing this!
this.name = name;
this.age = age;
}
}

The University of Sydney Page 48


Constructor Overloading
Let’s take a look at the following class
public class Person {

private static int DEFAULT_AGE = 21;

private String name;


private int age;

public Person() {
name = "Jeff";
age = DEFAULT_AGE;
}

public Person(String name) {


this.name = name;
We can see that there are
3 different constructors. this.age = DEFAULT_AGE;
Within our own code we }
choose to call anyone, in
fact we have already been
public Person(String name, int age) {
doing this!
public static void main(String[] args) { this.name = name;
this.age = age; Since each constructor has a
Person p1 = new Person(); //Jeff the default person!
unique signature, we are
Person p2 = new Person("Janice"); } able to utilise specific
}
Person p3 = new Person("Dave", 32); constructors by satisfying
} the correct types.
The University of Sydney Page 49
this keyword

The this keyword can play an important role in regards to


constructors. It allows us to refer to the constructor within the
context of a class.

In particular, we can reduce the amount of code we write by


reusing a constructor.

The University of Sydney Page 50


Constructor Overloading

How could we use the this keyword in this example?


public class Person { public class Person {

private static int DEFAULT_AGE = 21; private static int DEFAULT_AGE = 21;
private String name; private String name;
private int age; private int age;

public Person() { public Person() {


name = "Jeff"; this("Jeff", DEFAULT_AGE);
age = DEFAULT_AGE; }
}
public Person(String name) {
public Person(String name) { this(name, DEFAULT_AGE);
this.name = name; }
this.age = DEFAULT_AGE;
} public Person(String name, int age) {
this.name = name;
public Person(String name, int age) { this.age = age;
this.name = name; }
this.age = age; }
}
}
The University of Sydney Page 51
Constructor Overloading

How could we use the this keyword in this example?


public class Person { public class Person {

private static int DEFAULT_AGE = 21; private static int DEFAULT_AGE = 21;
private String name; private String name;
private int age; private int age;

public Person() { public Person() {


name = "Jeff"; this("Jeff", DEFAULT_AGE);
age = DEFAULT_AGE; }
}
public Person(String name) {
public Person(String name) { this(name, DEFAULT_AGE);
this.name = name; }
this.age = DEFAULT_AGE;
} public Person(String name, int age) {
this.name = name;
public Person(String name, int age) { this.age = age;
this.name = name; }
this.age = age; }
}
}
The University of Sydney Page 52
Constructor Overloading

How could we use the this keyword in this example?


public class Person { public class Person {

private static int DEFAULT_AGE = 21; private static int DEFAULT_AGE = 21;
private String name; private String name;
private int age; private int age;

public Person() { public Person() {


name = "Jeff"; this("Jeff", DEFAULT_AGE);
age = DEFAULT_AGE; }
}
public Person(String name) {
By using the this keyword,
public Person(String name) { we are able to eliminate this(name, DEFAULT_AGE);
this.name = name; few lines from the other }
constructors by using the
this.age = DEFAULT_AGE;
last one. public Person(String name, int age) {
}
this.name = name;
public Person(String name, int age) { this.age = age;
this.name = name; }
this.age = age; }
}
}
The University of Sydney Page 53
super keyword

We saw the use of the super keyword. We will be exploring


inheritance with constructor overloading and method overriding
and how we are able to utilise inherited behaviour in our
program.

We will show how we are able to access elements through the


super keyword.

The University of Sydney Page 54


So how does it work with inheritance?

We saw before that we could specify the constructor we want to


use and using the super keyword.

Let’s bring in the Employee class to inherit from Person.

The University of Sydney Page 55


Constructor Overloading

public class Person { public class Employee extends Person {

private static int DEFAULT_AGE = 21; private long employeeId;


private long departmentId;
private String name;
private int age; public Employee(String name, int age,
long departmentId, long employeeId) {

public Person() {
super(name, age);
this("Jeff", DEFAULT_AGE);
this.departmentId = departmentId;
}
this.employeeId = employeeId;
}
public Person(String name) { //<snipped other methods
this(name, DEFAULT_AGE); }
}

public Person(String name, int age) {


this.name = name;
this.age = age;
}
//<snipped getName(), setName(), getAge()
}

The University of Sydney Page 56


Constructor Overloading

public class Person { public class Employee extends Person {

private static int DEFAULT_AGE = 21; private long employeeId;


private long departmentId;
private String name;
private int age; public Employee(String name, int age,
long departmentId, long employeeId) {

public Person() {
super(name, age);
this("Jeff", DEFAULT_AGE);
this.departmentId = departmentId;
}
this.employeeId = employeeId;
}
public Person(String name) { //<snipped other methods
this(name, DEFAULT_AGE); }
}

public Person(String name, int age) {


this.name = name; We are able to specify the
constructor we want to
this.age = age;
invoke and set attributes
} for the object.
//<snipped getName(), setName(), getAge()
}

The University of Sydney Page 57


Demonstration

The University of Sydney Page 58


Java IO
Overloading is not just restricted to methods, we are able to apply it to
constructors. This is evident within the standard library itself as well!

The University of Sydney Page 59


Constructor Summary, Oracle (https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html)
Java IO
Overloading is not just restricted to methods, we are able to apply it to
constructors. This is evident within the standard library itself as well!

We can see two different


methods we have been
using for Files and the
other for Standard Input.

The University of Sydney Page 60


Constructor Summary, Oracle (https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html)
Exceptions

You are bound to have come across an exception while


programming with Java. We will be introducing the concept of
throwable methods.

Looking at the Scanner class, we can observe that some


constructors and methods require wrapping around a try-catch
block.

However, not all exceptions require this.

Like with IO, Exceptions have an inheritance hierarchy and


contain specific error messages to inform the programmer of the
error that has occurred.

The University of Sydney Page 61


Exceptions

Whoa! That’s a lot of


subclasses!

The University of Sydney Page 62 62


Exception Class, Oracle (https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Exception.html)
Exceptions

Let’s tackle the two major Exception classes that dictate how the
rest operate.

● Exception and any subclasses (with the exception of


RuntimeException) is a checked exception

This means that when a method can throw the exception,


the programmer must handle it using a try-catch block.

● RuntimeException and any subclasses, is an unchecked


exception. The programmer does not need to handle this
case but can catch if they want to.

This should be a case where the program should crash.

The University of Sydney Page 63


Checked Exception

Let’s examine the following

public void imGonnaCrash() throws Exception {


throw new Exception("Definitely crashing!");
}

The University of Sydney Page 64


Checked Exception

Let’s examine the following

public void imGonnaCrash() throws Exception {


throw new Exception("Definitely crashing!");
}

Since the method can throw a


checked exception we are required
Where we throw the exception, it to handle it when we call it.
typically this is in some kind of if
statement.

The University of Sydney Page 65


Checked Exception

Let’s examine the following

public void imGonnaCrash() throws Exception {


throw new Exception("Definitely crashing!");
}

Within our main method we cannot proceed with the following.

public static void main(String[] args) {


imGonnaCrash();
}

The University of Sydney Page 66


Checked Exception

Let’s examine the following

public void imGonnaCrash() throws Exception {


throw new Exception("Definitely crashing!");
}

We are forced to catch it by the compiler;.

public static void main(String[] args) {


try {
imGonnaCrash();
} catch(Exception e) {
e.printStackTrace();
}
}
The University of Sydney Page 67
Runtime Exception

Let’s examine the following

public void imGonnaCrash() {


throw new RuntimeException("Definitely crashing!");
}

Where the compiler will not force the programmer to handle a


RuntimeException.

public static void main(String[] args) {


imGonnaCrash();
}

The University of Sydney Page 68


Let’s see how throwing exceptions work

The University of Sydney Page 69


See you next time!

The University of Sydney Page 70

You might also like