+ All Categories
Home > Documents > Object Oriented Programming in Java - University of...

Object Oriented Programming in Java - University of...

Date post: 14-Apr-2018
Category:
Upload: domien
View: 215 times
Download: 1 times
Share this document with a friend
41
Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial Intelligence Object Oriented II
Transcript
Page 1: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Object Oriented Programming in

Java

Mr. Charlie AbelaDept. of Artificial Intelligence

Mr. Charlie AbelaDept. of Artificial Intelligence

Object Oriented IIObject Oriented II

Page 2: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 2

Objectives

Getting familiar with – Inheritance

• subclass and superclass concept• super reserved word• overloading and overriding methods• Object class • toString method

– visibility modifiers– this keyword– data encapsulation– Java class library (API)

Getting familiar with – Inheritance

• subclass and superclass concept• super reserved word• overloading and overriding methods• Object class • toString method

– visibility modifiers– this keyword– data encapsulation– Java class library (API)

Page 3: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 3

Inheritance

One of the fundamental concepts in object oriented programming and design is inheritanceAdvantage: reuse of codeInheritance can be either explicit of implicit.Whenever a class is created, it implicitly inherits from the most generic Java class: Object

This makes the Object class the superclass (parent, base class or supertype) of all classes.All other classes can be considered as subclasses (child, subtype or extended) of the Object classA class inherits from another class, all accessible data fields & methodsBUT may add new fields and methods

One of the fundamental concepts in object oriented programming and design is inheritanceAdvantage: reuse of codeInheritance can be either explicit of implicit.Whenever a class is created, it implicitly inherits from the most generic Java class: Object

This makes the Object class the superclass (parent, base class or supertype) of all classes.All other classes can be considered as subclasses (child, subtype or extended) of the Object classA class inherits from another class, all accessible data fields & methodsBUT may add new fields and methods

Page 4: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 4

Example

Rectangle

-colour:String = "white"-dateCreated:java.util.Date-width:double = 1.0-length:double = 1.0+Rectangle()+Rectangle(w:double, l:double)+setColour(col:String):void+getColour():String+getDateCreated():java.util.Date+setWidth(w:double):void+getWidth():double+setLength(l:double):void+getLength():double+toString():String

Circle

-colour:String = "green"-dateCreated:java.util.Date-radius:double = 1.0

+Circle()+Circle(r:double)+setColour(col:String):void+getColour():String+getDateCreated():java.util.Date+setRadius(r:double):void+getRadius():double+toString():String

Common data– colour and dateCreated

Common methods (behaviour)– setColour and getColour– getDateCreated– toString

Common data– colour and dateCreated

Common methods (behaviour)– setColour and getColour– getDateCreated– toString

Unified Modelling Language provides a design mechanism which allows depiction of classes and relationships with other classes

Unified Modelling Language provides a design mechanism which allows depiction of classes and relationships with other classes

Page 5: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 5

Inheritance mechanism

a Rectangle is-A Shapea Square is-A Shapea Circle is-A Shapea ColouredSquare is-A Square

a Rectangle is-A Shapea Square is-A Shapea Circle is-A Shapea ColouredSquare is-A Square

Square

Shape

Rectangle Circle Triangle

ColouredSquare _3DSquare BorderedSquare

Page 6: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 6

Inheritance mechanism II

The is-A relationship is also referred to as a Generalisationrelationship.In fact a parent class is considered to be more generic then a subclass, or a subclass is more specific then its super/parent class.A Rectangle class has all the properties and methods of a ShapeBut it has its own specific properties and methods as well

The is-A relationship is also referred to as a Generalisationrelationship.In fact a parent class is considered to be more generic then a subclass, or a subclass is more specific then its super/parent class.A Rectangle class has all the properties and methods of a ShapeBut it has its own specific properties and methods as well

Page 7: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 7

Class diagram

Shape

-colour:String = "white"-dateCreated: java.util.Date

+ Shape()+setColour(col: String): void+getColour(): String+getDateCreated():java.util.Date+toString():String

Rectangle

-width:double = 1.0-length:double = 1.0

+Rectangle()+Rectangle(w:double, l:double)+setWidth(w:double):void+getWidth():double+setLength(l:double):void+getLength():double+toString():String+calculateArea():double

Circle

-radius:double = 1.0

+Circle()+Circle(r:double)+setRadius(r:double):void+getRadius():double+toString():String+calculateArea():double

Page 8: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 8

Explicit inheritance

Explicit inheritance is achieved through the extends keyword

public class Shape{//data fields and methods

}public class Circle extends Shape{

//own data fields and methods}public class Rectangle extends Shape{

//own data fields and methods}

This means that data fields and methods in the Shape class are explicitly inherited by the Circle and Rectangle classes i.e. no need to re-implement them.

Explicit inheritance is achieved through the extends keyword

public class Shape{//data fields and methods

}public class Circle extends Shape{

//own data fields and methods}public class Rectangle extends Shape{

//own data fields and methods}

This means that data fields and methods in the Shape class are explicitly inherited by the Circle and Rectangle classes i.e. no need to re-implement them.

Page 9: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 9

Shape class

import java.util.Date;

public class Shape{private String colour = “white”;private Date dateCreated;

public Shape(){dateCreated = new Date();

}public void setColour(String col){

colour = col;}public String getColour(){

return colour;}public Date getDateCreated(){

return dateCreated;}public String toString(){return getColour()+” shape created on “+getDateCreated();}

}

import java.util.Date;

public class Shape{private String colour = “white”;private Date dateCreated;

public Shape(){dateCreated = new Date();

}public void setColour(String col){

colour = col;}public String getColour(){

return colour;}public Date getDateCreated(){

return dateCreated;}public String toString(){return getColour()+” shape created on “+getDateCreated();}

}

Page 10: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 10

Circle class

public class Circle extends Shape{private double radius;

public Circle(){radius = 0;

}public Circle(double r){

radius = r;}public void setRadius(double r){

radius = r;}public double getRadius(){

return radius;}public double calculateArea(){

double r = getRadius();return Math.PI *r*r;

}}

public class Circle extends Shape{private double radius;

public Circle(){radius = 0;

}public Circle(double r){

radius = r;}public void setRadius(double r){

radius = r;}public double getRadius(){

return radius;}public double calculateArea(){

double r = getRadius();return Math.PI *r*r;

}}

Page 11: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 11

Explicit inheritance II

public class UsingShapes{public static void main(String[] args){Circle nc = new Circle(3.4);nc.setColour(“green”); //inheritedSystem.out.println(nc.toString());//inheritedSystem.out.printf(“%.2f”,nc.calculateArea());

Rectangle rt = new Rectangle(2.3,4.1);rt.setColour(“green”); //inheritedSystem.out.println(rt.toString());//inheritedSystem.out.printf(“%.2f”,rt.calculateArea());

}}

Even though setColour and toStringmethods are defined in the Shape class these can be used by extended classes as if they implemented by them

public class UsingShapes{public static void main(String[] args){Circle nc = new Circle(3.4);nc.setColour(“green”); //inheritedSystem.out.println(nc.toString());//inheritedSystem.out.printf(“%.2f”,nc.calculateArea());

Rectangle rt = new Rectangle(2.3,4.1);rt.setColour(“green”); //inheritedSystem.out.println(rt.toString());//inheritedSystem.out.printf(“%.2f”,rt.calculateArea());

}}

Even though setColour and toStringmethods are defined in the Shape class these can be used by extended classes as if they implemented by them

Page 12: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 12

Overview of packages

Packages are used to group classes together

java.lang

Reasons for using packages– easily locate classes– avoid naming conflicts– easily distribute software– as a means of protection

Packages are hierarchical in nature and may contain other packages

javax.swing.border

Package declaration is specified as the first non-comment and nonblank statement in a program.

Packages are used to group classes together

java.lang

Reasons for using packages– easily locate classes– avoid naming conflicts– easily distribute software– as a means of protection

Packages are hierarchical in nature and may contain other packages

javax.swing.border

Package declaration is specified as the first non-comment and nonblank statement in a program.

Page 13: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 13

geometry package

Such a package may contain a folder called shapes which contains the classes, Shape, Rectangle, Circle, Square, Triangle etc.

Such a package may contain a folder called shapes which contains the classes, Shape, Rectangle, Circle, Square, Triangle etc.

geometry

shapes

Rectangle

Shape

Triangle

Circle

Square

package geometry.shapes;package geometry.shapes;

Page 14: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 14

this Keyword

Sometimes it is needed to reference a hidden variableOtherwise it is possible to useprivate String colour = “white”;public void setColour(String colour){

this.colour = colour;}

ORpublic class Circle{

private double radius;public Circle(double radius){

this.radius = radius;}

this always refers to the currently executing object, i.e. the object running the code where the reference is.

Sometimes it is needed to reference a hidden variableOtherwise it is possible to useprivate String colour = “white”;public void setColour(String colour){

this.colour = colour;}

ORpublic class Circle{

private double radius;public Circle(double radius){

this.radius = radius;}

this always refers to the currently executing object, i.e. the object running the code where the reference is.

Page 15: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 15

Visibility modifiers

Access or Visibility modifiers– allow or disallow code in one class

to have access to a member of another class

– determine whether a subclass can inherit a member of its superclass

A class can have only two of the four access level control offered by Java:

– default and public

The other modifiers are– protected and private

default is implicitly associated with any class, method or variable whenever no modifier is specified.

Access or Visibility modifiers– allow or disallow code in one class

to have access to a member of another class

– determine whether a subclass can inherit a member of its superclass

A class can have only two of the four access level control offered by Java:

– default and public

The other modifiers are– protected and private

default is implicitly associated with any class, method or variable whenever no modifier is specified.

Page 16: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 16

Accessing MethodsSportsCar

goFast(){ }

doStuff() { goFast(); }

Convertible

doThings(){ SportsCar sc = new SportsCar(); sc.goFast();}

doMore() { goFast(); }

Driver

doDriverStuff(){ SportsCar car = new SportsCar(); car.goFast();

Convertable con = new Convertable(); con.goFast(); }

D invoke a method declared in the same class

R invoke a method through a reference of the class

I invoking an inherited method

R

I

D

R

R

Page 17: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 17

public modifier

When a variable or method are declared to be public, then they are visible from all other classes, regardless of the package they are in.

When a variable or method are declared to be public, then they are visible from all other classes, regardless of the package they are in.

package geometry;import test.*;public class TestShapes{

public static void main(String[] args){TestCircle tc = new TestCircle();tc.testIt();

}}

package geometry;import test.*;public class TestShapes{

public static void main(String[] args){TestCircle tc = new TestCircle();tc.testIt();

}}

package test;public class TestCircle{

public void testIt(){System.out.println(“testing Circle”);

}}

package test;public class TestCircle{

public void testIt(){System.out.println(“testing Circle”);

}}

Page 18: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 18

public modifier II

If a member in a parent class is declared as public, the subclass inherits that member regardless of the package.

If a member in a parent class is declared as public, the subclass inherits that member regardless of the package.

package geometry.shapes;public class Square{

public String doSquareStuff(){return “square stuff done”;

}}

package geometry.shapes;public class Square{

public String doSquareStuff(){return “square stuff done”;

}}

package geometry.mdshapes;public class _3dSquare extends Square{

public void testSquare(){System.out.println(doSquareStuff());

}}

package geometry.mdshapes;public class _3dSquare extends Square{

public void testSquare(){System.out.println(doSquareStuff());

}}

Page 19: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 19

private modifier

Members in a class that are marked as private cannot be accessed by code outside that classThis applies also when a class inherits from its parent class, i.e. a method or variable marked as private in class A is not visible outside class A and therefore subclass B cannot access it.

Members in a class that are marked as private cannot be accessed by code outside that classThis applies also when a class inherits from its parent class, i.e. a method or variable marked as private in class A is not visible outside class A and therefore subclass B cannot access it.

Page 20: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 20

Example I

Code will generate a compilation error. Though TestCircle reference is ok, cannot invoke testIt method.

Code will generate a compilation error. Though TestCircle reference is ok, cannot invoke testIt method.

package geometry;import test.*;public class TestShapes{

public static void main(String[] args){TestCircle tc = new TestCircle();tc.testIt(); //compiler error

}}

package geometry;import test.*;public class TestShapes{

public static void main(String[] args){TestCircle tc = new TestCircle();tc.testIt(); //compiler error

}}

package test;public class TestCircle{

private void testIt(){System.out.println(“testing Circle”);

}}

package test;public class TestCircle{

private void testIt(){System.out.println(“testing Circle”);

}}

Page 21: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 21

Example II

Code in testSquare will generate a compilation error. doSquareStuff is not inherited

Code in testSquare will generate a compilation error. doSquareStuff is not inherited

package geometry.shapes;public class Square{

private String doSquareStuff(){return “square stuff done”;

}}

package geometry.shapes;public class Square{

private String doSquareStuff(){return “square stuff done”;

}}

package geometry.shapes; //same packagepublic class _3dSquare extends Square{

public void testSquare(){//generates an errorSystem.out.println(doSquareStuff());

}}

package geometry.shapes; //same packagepublic class _3dSquare extends Square{

public void testSquare(){//generates an errorSystem.out.println(doSquareStuff());

}}

Page 22: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 22

Default

Default protection is implicitly associated with any variable, method or class whose access modifiers are not defined.Examples:class DefaultClass{}String getStuff(){}; int x = 9;

A default member can only be accessed if the class accessing that member belongs to the same packagedefault implies package access

Default protection is implicitly associated with any variable, method or class whose access modifiers are not defined.Examples:class DefaultClass{}String getStuff(){}; int x = 9;

A default member can only be accessed if the class accessing that member belongs to the same packagedefault implies package access

Page 23: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 23

Example I

Code gives a compilation error since testIt is not visible from within TestShapes, because it is in a different package

Code gives a compilation error since testIt is not visible from within TestShapes, because it is in a different package

package geometry;import test.*;public class TestShapes{

public static void main(String[] args){TestCircle tc = new TestCircle();tc.testIt(); //compiler error

}}

package geometry;import test.*;public class TestShapes{

public static void main(String[] args){TestCircle tc = new TestCircle();tc.testIt(); //compiler error

}}

package test;public class TestCircle{

void testIt(){ //default accessSystem.out.println(“testing Circle”);

}}

package test;public class TestCircle{

void testIt(){ //default accessSystem.out.println(“testing Circle”);

}}

Page 24: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 24

Example II

Code in testSquare will generate an error when invoking doSquareStuff. This has default access and is only visible at same package level.

Code in testSquare will generate an error when invoking doSquareStuff. This has default access and is only visible at same package level.

package geometry.shapes;public class Square{

String doSquareStuff(){ //default accessreturn “square stuff done”;

}}

package geometry.shapes;public class Square{

String doSquareStuff(){ //default accessreturn “square stuff done”;

}}

package geometry.mdshapes;public class _3dSquare extends Square{

public void testSquare(){//generates compiler errorSystem.out.println(doSquareStuff());

}}

package geometry.mdshapes;public class _3dSquare extends Square{

public void testSquare(){//generates compiler errorSystem.out.println(doSquareStuff());

}}

Page 25: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 25

protected Modifier

This is similar to default access, accept where subclasses are involved.protected => package + subclasses

This means that a subclass may have access to its superclass members, declared as protected, even if the two classes (parent and child) are in different packagesHowever this access is strictlythrough inheritance

This is similar to default access, accept where subclasses are involved.protected => package + subclasses

This means that a subclass may have access to its superclass members, declared as protected, even if the two classes (parent and child) are in different packagesHowever this access is strictlythrough inheritance

Page 26: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 26

Example I

No compilation error is generated, since doSquareStuff is invoked through inheritance

No compilation error is generated, since doSquareStuff is invoked through inheritance

package geometry.shapes;public class Square{

protected String doSquareStuff(){return “square stuff done”;

}}

package geometry.shapes;public class Square{

protected String doSquareStuff(){return “square stuff done”;

}}

package geometry.mdshapes;public class _3dSquare extends Square{

public void testSquare(){//this is okSystem.out.println(doSquareStuff());

}}

package geometry.mdshapes;public class _3dSquare extends Square{

public void testSquare(){//this is okSystem.out.println(doSquareStuff());

}}

Page 27: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 27

Example II

This generates a compilation error, since testSquare is trying to access doSquareStuff through a reference to Square

This generates a compilation error, since testSquare is trying to access doSquareStuff through a reference to Square

package geometry.shapes;public class Square{

protected String doSquareStuff(){return “square stuff done”;

}}

package geometry.shapes;public class Square{

protected String doSquareStuff(){return “square stuff done”;

}}

package geometry.mdshapes;public class _3dSquare extends Square{

public void testSquare(){Square sq = new Square(4);//generates a compiler errorSystem.out.println(sq.doSquareStuff());

}}

package geometry.mdshapes;public class _3dSquare extends Square{

public void testSquare(){Square sq = new Square(4);//generates a compiler errorSystem.out.println(sq.doSquareStuff());

}}

Page 28: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 28

Accessor methods

Ideally an object's instance variables areencapsulated within the object (i.e. hidden inside and safe from inspection or manipulation by other objects. With certain well-defined exceptions, the object's methods are the only means by which other objects can inspect or alter an object's instance variables. Encapsulation of an object's data protects the object from corruption by other objects and conceals an object's implementation details from outsiders.This encapsulation of data behind an object's methods is one of the cornerstones of object-oriented programming.

Ideally an object's instance variables areencapsulated within the object (i.e. hidden inside and safe from inspection or manipulation by other objects. With certain well-defined exceptions, the object's methods are the only means by which other objects can inspect or alter an object's instance variables. Encapsulation of an object's data protects the object from corruption by other objects and conceals an object's implementation details from outsiders.This encapsulation of data behind an object's methods is one of the cornerstones of object-oriented programming.

Page 29: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 29

Accessor methods II

Such methods are called accessor methodsConventionally in Java these methods are often termed get and set methods.Hidden instance variable colourprivate String colour;

Set methods have a list of parameters and return void

public void setColour(String col){colour = col;

}

Get methods have no parameters and return some type

public String getColour(){return colour;

}

Such methods are called accessor methodsConventionally in Java these methods are often termed get and set methods.Hidden instance variable colourprivate String colour;

Set methods have a list of parameters and return void

public void setColour(String col){colour = col;

}

Get methods have no parameters and return some type

public String getColour(){return colour;

}

Page 30: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 30

More on Constructors

Revisiting the Circle class using the this keyword

public class Circle{private float radius;private String colour;//constructor to initialise private //instance variablespublic Circle(float radius, String colour){

this.radius = radius;this.colour = colour;

}}

Through the this keyword we can differentiate between variables (local and instance)

Revisiting the Circle class using the this keyword

public class Circle{private float radius;private String colour;//constructor to initialise private //instance variablespublic Circle(float radius, String colour){

this.radius = radius;this.colour = colour;

}}

Through the this keyword we can differentiate between variables (local and instance)

Page 31: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 31

Call Overloaded Constructors

Using this() (as the 1st statement in a constructor) it is possible to call an overloaded constructor

private float x,y; public Square(){

//call to Square(float,float)this(1.0f, 1.0f);

}public Square(float x, float y){

System.out.println("New Square");// initialise instance variablesthis.x = x;this.y = y;

}

Using this() (as the 1st statement in a constructor) it is possible to call an overloaded constructor

private float x,y; public Square(){

//call to Square(float,float)this(1.0f, 1.0f);

}public Square(float x, float y){

System.out.println("New Square");// initialise instance variablesthis.x = x;this.y = y;

}

Page 32: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 32

Constructor chaining

public class Rectangle { private int x, y; private int width, height;

public Rectangle() { this(0, 0, 0, 0);

}

public Rectangle(int width, int height) { this(0, 0, width, height);

}

public Rectangle(int x, int y, int width, int height) {

this.x = x; this.y = y; this.width = width; this.height = height;

} ...

}

public class Rectangle { private int x, y; private int width, height;

public Rectangle() { this(0, 0, 0, 0);

}

public Rectangle(int width, int height) { this(0, 0, width, height);

}

public Rectangle(int x, int y, int width, int height) {

this.x = x; this.y = y; this.width = width; this.height = height;

} ...

}

Page 33: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 33

super keyword

A constructor can have as its first statement also

– a call to super()super() actually invokes the constructor in a superclass.super can also be called with arguments.If a constructor does not explicitly make a call to super(), this is implicitly done, nevertheless. So be careful to avoid unnecessary compilation errors

A constructor can have as its first statement also

– a call to super()super() actually invokes the constructor in a superclass.super can also be called with arguments.If a constructor does not explicitly make a call to super(), this is implicitly done, nevertheless. So be careful to avoid unnecessary compilation errors

Page 34: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 34

Using super()

public class Shape{

private String colour;//constructor to initialise private //instance variablespublic Shape(String colour){

this.colour = colour;}

}

public class Square extends Shape{private x, y float;

public Square(String c, float x, float y){super(c); //call to super constructorthis.x = x;this.y = y;

}}

public class Shape{

private String colour;//constructor to initialise private //instance variablespublic Shape(String colour){

this.colour = colour;}

}

public class Square extends Shape{private x, y float;

public Square(String c, float x, float y){super(c); //call to super constructorthis.x = x;this.y = y;

}}

Page 35: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 35

Using super() II

However this will generate a compilation errorpublic class Square{

private x, y float;public Square(String c, float x, float y){

super(); //invoke no arg. constructorthis.x = x;this.y = y;

}}

However this will generate a compilation errorpublic class Square{

private x, y float;public Square(String c, float x, float y){

super(); //invoke no arg. constructorthis.x = x;this.y = y;

}}

So will thispublic class Square{

private x, y float;public Square(String c, float x, float y){

this.x = x;this.y = y;

}}

So will thispublic class Square{

private x, y float;public Square(String c, float x, float y){

this.x = x;this.y = y;

}}

Page 36: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 36

Method Overriding

Method overriding involves the creation of another method (in a subclass) which has the same signature as a method in the superclass.

public class Shape{public String toString(){

return “This is a Shape object”;}

}public class Square extends Shape{

public String toString(){return “This is a Square object”;

}}

The toString method in general is used to create a String representation of the Object

Method overriding involves the creation of another method (in a subclass) which has the same signature as a method in the superclass.

public class Shape{public String toString(){

return “This is a Shape object”;}

}public class Square extends Shape{

public String toString(){return “This is a Square object”;

}}

The toString method in general is used to create a String representation of the Object

Page 37: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 37

Method Overriding II

It is not possible to override a method which is marked as final or as staticThe access level cannot be more restrictive than that of the overridden method’s. However it can be less.In essence, if a method cannot be inherited for some reason, then it cannot be overridden.

It is not possible to override a method which is marked as final or as staticThe access level cannot be more restrictive than that of the overridden method’s. However it can be less.In essence, if a method cannot be inherited for some reason, then it cannot be overridden.

Page 38: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 38

Object class

The Object class, in the java.langpackage.It is at the top of the class hierarchy tree and every class is a direct or indirect descendant of this class. Every class (that is used or created) inherits the instance methods of Object.

The Object class, in the java.langpackage.It is at the top of the class hierarchy tree and every class is a direct or indirect descendant of this class. Every class (that is used or created) inherits the instance methods of Object.

Page 39: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 39

Object class II

Some Methods from the Object classprotected Object clone() throws CloneNotSupportedException

– Creates and returns a copy of this object. public boolean equals(Object obj)

– Indicates whether some other object is "equal to" this one.

protected void finalize() throws Throwable

– Called by the garbage collector on an object when garbage collection determines that there are no more references to the object (more on this later)

public String toString()

– Returns a string representation of the object.

Some Methods from the Object classprotected Object clone() throws CloneNotSupportedException

– Creates and returns a copy of this object. public boolean equals(Object obj)

– Indicates whether some other object is "equal to" this one.

protected void finalize() throws Throwable

– Called by the garbage collector on an object when garbage collection determines that there are no more references to the object (more on this later)

public String toString()

– Returns a string representation of the object.

Page 40: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 40

Java API

The Java class library contains thousands of predefined classes and interfaces that programmers can use to write their own applications. These classes are grouped into packages based on their functionality. For example, the javax.swing gathers packages and classes related to GUI creationThe Java API documentation lists the public and protected members of each class and the public members of each interface in the Java class library. The documentation overviews all the classes and interfaces, it summarizes their members (i.e., the fields, constructors and methods of classes, and the fields and methods of interfaces) and provides detailed descriptions of each

The Java class library contains thousands of predefined classes and interfaces that programmers can use to write their own applications. These classes are grouped into packages based on their functionality. For example, the javax.swing gathers packages and classes related to GUI creationThe Java API documentation lists the public and protected members of each class and the public members of each interface in the Java class library. The documentation overviews all the classes and interfaces, it summarizes their members (i.e., the fields, constructors and methods of classes, and the fields and methods of interfaces) and provides detailed descriptions of each

Page 41: Object Oriented Programming in Java - University of Maltastaff.um.edu.mt/cabe2/lectures/mit/slides/unit_6.pdf · Object Oriented Programming in Java Mr. Charlie Abela Dept. of Artificial

Charlie Abela OOP II © 41

Java API II

Most Java programmers rely on this documentation when writing programs. Normally, programmers would search the API to find the following:

– The package that contains a particular class or interface.

– Relationships between a particular class or interface and other classes and interfaces.

– Class or interface constants—normally declared as public static final fields.

– Constructors to determine how an object of the class can be initialized.

– The methods of a class to determine whether they are static or non-static, the number and types of the arguments you need to pass, the return types and any exceptions that might be thrown from the method.

– In addition, programmers often rely on the documentation to discover classes and interfaces that they have not used before.

Most Java programmers rely on this documentation when writing programs. Normally, programmers would search the API to find the following:

– The package that contains a particular class or interface.

– Relationships between a particular class or interface and other classes and interfaces.

– Class or interface constants—normally declared as public static final fields.

– Constructors to determine how an object of the class can be initialized.

– The methods of a class to determine whether they are static or non-static, the number and types of the arguments you need to pass, the return types and any exceptions that might be thrown from the method.

– In addition, programmers often rely on the documentation to discover classes and interfaces that they have not used before.


Recommended