Transcript
Page 1: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

EE2E1. JAVA Programming

Lecture 3Lecture 3

InheritanceInheritance

Page 2: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Contents Base classes and derived classesBase classes and derived classes Protected scope Protected scope Inheritance hierarchiesInheritance hierarchies The IS-A relationshipThe IS-A relationship PolymorphismPolymorphism Abstract classesAbstract classes Superclass Superclass ObjectObject

Page 3: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Base classes and derived classes Inheritance is a fundamental requirement Inheritance is a fundamental requirement

for object orientationfor object orientation Inheritance allows new classes to be Inheritance allows new classes to be

derived derived from existing classesfrom existing classes Existing methods can be changed and extra Existing methods can be changed and extra

instance fields can be added in the derived instance fields can be added in the derived classclass

Page 4: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Example A A StudentStudent class represents basic information class represents basic information

about students at the Universityabout students at the University There are many categories of studentsThere are many categories of students We can think about We can think about extending extending the the StudentStudent

class to representclass to represent Undergraduate studentsUndergraduate students Postgraduate studentsPostgraduate students

Each extension requires additional instance Each extension requires additional instance fieldsfields

Page 5: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

classclass UndergradStudent UndergradStudent represents the basic represents the basic student informationstudent information namename id. numberid. number addressaddress

It also represents undergraduate specific It also represents undergraduate specific informationinformation degree programmedegree programme

Page 6: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Likewise classLikewise class PostgradStudent PostgradStudent represents represents the basic student informationthe basic student information namename id. numberid. number addressaddress

It also represents postgraduate specific It also represents postgraduate specific informationinformation research supervisorresearch supervisor

Page 7: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

public class Studentpublic class Student{{

public Student(String n, int id, String a)public Student(String n, int id, String a){ { name=new String(n); idNumber=id; address=new String(a);name=new String(n); idNumber=id; address=new String(a);

}}

public void printInfo()public void printInfo(){{

System.out.println(name + “ ”+ idNumber + “ ” + address);System.out.println(name + “ ”+ idNumber + “ ” + address);}}

private String name;private String name;private int idNumber;private int idNumber;private String address;private String address;

}}

Page 8: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

public class UndergradStudent extends Studentpublic class UndergradStudent extends Student{{

public UndergradStudent(String n, int id, String a, String d)public UndergradStudent(String n, int id, String a, String d){ { super(n,id,a);super(n,id,a); degreeProgramme=new String(d);degreeProgramme=new String(d);}}

public void printInfo()public void printInfo(){{ super.printInfo();super.printInfo(); System.out.println(degreeProgramme);System.out.println(degreeProgramme);}}

private String degreeProgramme;private String degreeProgramme;}}

Page 9: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

public class PostgradStudent extends Studentpublic class PostgradStudent extends Student{{

public PostgradStudent(String n, int id, String a, String p)public PostgradStudent(String n, int id, String a, String p){ { super(n,id,a);super(n,id,a); projectSupervisor=new String(p);projectSupervisor=new String(p);

}}

public void printInfo()public void printInfo(){{

super.printInfo();super.printInfo(); System.out.println(projectSupervisor);System.out.println(projectSupervisor);

}}

private String projectSupervisor;private String projectSupervisor;}}

Page 10: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

public class StudentTest{

public static void main(String[] args){

UndergradStudent s1=new UndergradStudent(“John Smith”, 3429, “21 Bristol Rd”, “Electrical Eng”);

PostgradStudent s2=new PostgradStudent(“Alan Jones”, 5395, “30 Bournbrook Rd”,“Dr. Mike Spann”);

s1. printInfo();

s2.printInfo();}

}

Page 11: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Keyword Keyword extendsextends means we are making a means we are making a new class which derives from an existing new class which derives from an existing classclass

The new class is the The new class is the derivedderived class and the class and the existing class is the existing class is the basebase class class StudentStudent is the base class is the base class Classes Classes PostgradStudentPostgradStudent and and

UndergradStudentUndergradStudent are derived classes are derived classes Also the terms Also the terms superclasssuperclass (base class) and (base class) and

subclasssubclass (derived class) are often used (derived class) are often used

Page 12: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

A key point is that private instance fields in A key point is that private instance fields in the base class cannot be accessed by the base class cannot be accessed by derived class methodsderived class methods

The derived class constructor invokes the The derived class constructor invokes the base class constructor through the call to base class constructor through the call to super(…)super(…) Must be the first statement in the derived Must be the first statement in the derived

class constructorclass constructor Avoids the derived class having to access Avoids the derived class having to access

private instance fields in order to private instance fields in order to initialize theminitialize them

Page 13: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Protected scope

Protected scope gives a derived class access Protected scope gives a derived class access to base class instance fields and methods to base class instance fields and methods declared as declared as protectedprotected

Breaks encapsulation only in the inheritance Breaks encapsulation only in the inheritance hierarchyhierarchy

Page 14: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

class myClassclass myClass{{

..

..protected int member;protected int member;

}}

class anotherClass extends myClassclass anotherClass extends myClass{{

public f() public f() { {

member=1;member=1; // OK – member protected// OK – member protected}}....

}}

Page 15: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Summary of member scope

ScopeScope KeywordKeyword Visible (where)?Visible (where)?

PrivatePrivate privateprivate In encapsulating In encapsulating classclass

ProtectedProtected protectedprotected In encapsulating In encapsulating class’s derived class’s derived classes or packageclasses or package

PublicPublic publicpublic Wherever the Wherever the encapsulating class encapsulating class is visibleis visible

Page 16: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Inheritance hierarchies

A simple tree diagram indicates the base A simple tree diagram indicates the base class/derived class relationshipclass/derived class relationship

Student

PostgradStudent UndergradStudent

Page 17: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

The hierarchy can easily be extendedThe hierarchy can easily be extended

Student

PostgradStudent UndergradStudent

PhDStudent MastersStudent

Page 18: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

The IS-A relationship

Any object that is an instance of a derived Any object that is an instance of a derived class must be useable in place of an object class must be useable in place of an object which is an instance of a base classwhich is an instance of a base class

Base class/derived class relationship form Base class/derived class relationship form an IS-A relationshipan IS-A relationship PostgradStudentPostgradStudent IS-A IS-A StudentStudent MastersStudent MastersStudent IS-A IS-A PostgradStudentPostgradStudent etcetc

Page 19: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

We can assign a derived class object to a We can assign a derived class object to a base class variablebase class variable

Becomes important for Becomes important for polymorphismpolymorphism

The converse is not legal – we can’t assign The converse is not legal – we can’t assign a base class object to a derived class a base class object to a derived class variablevariable Can use a cast but be careful!Can use a cast but be careful!

Page 20: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

public class StudentTest{

public static void main(String[] args){

Student[] s=new Student[2];

PostgradStudent ps=new PostgradStudent( “Alan Jones”, 5395, “30 Bournbrook Rd”,“Dr. Mike Spann”);

UndergradStudent us=new UndergradStudent(“John Smith”,

3429, “21 Bristol Rd”, “Electrical Eng”);

s[0]=ps; // legal assignments[1]=us; // legal assignment

ps=s[0]; // Error! }

}

Page 21: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Polymorphism

Crucial to object oriented programmingCrucial to object oriented programming

It is an object determining which method to It is an object determining which method to call depending on where it is in the call depending on where it is in the inheritance hierarchyinheritance hierarchy

While the method (argument and return While the method (argument and return types) might be the same, objects might types) might be the same, objects might respond differently respond differently

Page 22: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

When a method of a derived class is called When a method of a derived class is called through a reference to a base class objectthrough a reference to a base class object

The derived class method is called if The derived class method is called if there is a match (argument types and there is a match (argument types and return type)return type)

Otherwise the method call is passed to Otherwise the method call is passed to the base class (or to the next class up the the base class (or to the next class up the inheritance hierarchy)inheritance hierarchy)

The key is The key is late bindinglate binding. Code for the . Code for the method call is generated at runtimemethod call is generated at runtime

Page 23: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

public class Studentpublic class Student{{

..

..

public void displayFees()public void displayFees(){}{}

..

}}

Page 24: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

public class UndergradStudent extends Studentpublic class UndergradStudent extends Student{{

..

..

public void displayFees()public void displayFees(){{ System.out.println(“Undergrad. fees are £1000 pounds”);System.out.println(“Undergrad. fees are £1000 pounds”);}}

..

}}

Page 25: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

public class PostgradStudent extends Studentpublic class PostgradStudent extends Student{{

..

..

public void displayFees()public void displayFees(){{ System.out.println(“Postgrad. fees are £5000 pounds”);System.out.println(“Postgrad. fees are £5000 pounds”);}}

..

}}

Page 26: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

public classpublic class StudentTest StudentTest{{

public static void main(String[] args)public static void main(String[] args){{

Student[] s=new Student[2];Student[] s=new Student[2];

PostgradStudent ps=new PostgradStudent( PostgradStudent ps=new PostgradStudent( ““Alan Jones”, Alan Jones”, 5395, “30 Bournbrook Road”,5395, “30 Bournbrook Road”,““Dr. Mike Spann”); Dr. Mike Spann”);

UndergradStudent us=new UndergradStudent(UndergradStudent us=new UndergradStudent(““John Smith”,John Smith”, 3429, “21 Bristol Road”, 3429, “21 Bristol Road”, ““Electrical Eng”);Electrical Eng”);

s[0]=ps; s[0]=ps; // legal assignment// legal assignments[1]=us;s[1]=us; // legal assignment// legal assignment

s[0].displayFees();s[0].displayFees(); // Postgraduate fees displayed// Postgraduate fees displayeds[1].displayFees();s[1].displayFees(); // Undergraduate fees displayed// Undergraduate fees displayed

}}}}

Page 27: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Method Method displayFees() displayFees() exhibits different exhibits different functionality depending on the object functionality depending on the object making the callmaking the call

No obvious implementation of No obvious implementation of Student.displayFees()Student.displayFees() method – could make method – could make it abstract (see next section)it abstract (see next section)

However if a However if a displayFees()displayFees() method is not method is not present in the derived class, the call is present in the derived class, the call is passed up to the base classpassed up to the base class

Method calls are always passed up the Method calls are always passed up the inheritance chain until a match is foundinheritance chain until a match is found

Page 28: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Student

PostgradStudent UndergradStudent

s[]

Student.displayFees()

s[]

PostgradStudent.displayFees() s[]

UndergradStudent.displayFees()

Page 29: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

So why the big deal over polymorphism?So why the big deal over polymorphism? Easy to extend the hierarchyEasy to extend the hierarchy Simply add Simply add displayFees()displayFees() methods for methods for

new classes in the hierarchynew classes in the hierarchy Existing code will still work!Existing code will still work!

Student s=new Student(…);Student s=new Student(…);

MastersStudent ms=new MastersStudent(…); MastersStudent ms=new MastersStudent(…);

s=ms; s=ms; // legal assignment// legal assignment

s.displayFees();s.displayFees(); // Masters student fees displayed// Masters student fees displayed

Page 30: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Abstract classes At high levels in the inheritance hierarchy, classes At high levels in the inheritance hierarchy, classes

become more and more abstractbecome more and more abstract

The implementation of their methods becomes The implementation of their methods becomes less clear and more abstractless clear and more abstract

A call to an abstract method is always delegated A call to an abstract method is always delegated down to one of the derived class methodsdown to one of the derived class methods

A class containing at least one abstract method is A class containing at least one abstract method is called an called an abstract classabstract class

Java uses the keyword Java uses the keyword abstractabstract to denote abstract to denote abstract classes and methodsclasses and methods

Page 31: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

public abstract class Shapepublic abstract class Shape{{

public Shape(int x, int y){xpos=x; ypos=y;}public Shape(int x, int y){xpos=x; ypos=y;}

public void move(int dx, int dy){xpos+=dx; ypos+=dy;}public void move(int dx, int dy){xpos+=dx; ypos+=dy;}

public abstract float area();public abstract float area();

private int xpos, ypos;private int xpos, ypos;}}

public class Square extends Shapepublic class Square extends Shape{{

public Square(int x, int y, int s){super(x,y); side=s;}public Square(int x, int y, int s){super(x,y); side=s;}

public float area() {return side*side;}public float area() {return side*side;}

private int side;private int side;}}

Page 32: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

The method The method area()area() is abstract which makes the is abstract which makes the class class ShapeShape abstract abstract

A A ShapeShape object cannot be created object cannot be created

Shape s = new Shape(0,0);Shape s = new Shape(0,0); // Error!// Error!

We can have We can have ShapeShape object variables but they must object variables but they must refer to a derived class objectrefer to a derived class object

Shape sq = new Square(0,0,100);Shape sq = new Square(0,0,100); // OK// OKfloat a = sq.area();float a = sq.area();

The method The method move()move() is non-abstract and is not is non-abstract and is not overridden in the derived classesoverridden in the derived classes

Common functionality across the inheritance Common functionality across the inheritance hierarchyhierarchy

Page 33: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Superclass Object

Class Class Object Object is the ultimate ancestor of is the ultimate ancestor of every class in Java every class in Java

However, we don’t have to explicitly However, we don’t have to explicitly writewrite

class myClass extends Objectclass myClass extends Object

Useful for Useful for generic programminggeneric programming

Alternative is C++ template classes Alternative is C++ template classes which are more complexwhich are more complex

Page 34: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Example – a generic search algorithm We want a generic search algorithm to search for We want a generic search algorithm to search for anyany kind kind

of object in an arrayof object in an array Class Class ObjectObject provides an provides an equals()equals() method to test whether method to test whether

one object is equal to anotherone object is equal to another Simply checks if the 2 object references point to the Simply checks if the 2 object references point to the

same area of memorysame area of memory Not very useful in practice!Not very useful in practice!

We need to provide an We need to provide an equals()equals() method in the class of the method in the class of the object we are searching forobject we are searching for Polymorphism does the rest!Polymorphism does the rest!

Page 35: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

In the following example we are searching In the following example we are searching for a for a StudentStudent object in an array object in an array

The search is based on the student ID The search is based on the student ID numbernumber

Class Class SearchAlg SearchAlg provides a provides a linearSearchlinearSearch method which carries out the searchmethod which carries out the search

We have provided an implementation of We have provided an implementation of equals()equals() in class in class StudentStudent

Page 36: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

public class Studentpublic class Student{{

public Student(String n, int id, String a)public Student(String n, int id, String a){ { name=n; idNumber=id; address=a;name=n; idNumber=id; address=a;}}

public boolean equals(Object obj)public boolean equals(Object obj){{ Student s = (Student) obj;Student s = (Student) obj; return (idNumber==s.idNumber);return (idNumber==s.idNumber);}}

private String name;private String name;private int idNumber;private int idNumber;private String address;private String address;

}}

Page 37: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

public class SearchAlgpublic class SearchAlg{{

public static int linearSearch(Object[] a, Object b)public static int linearSearch(Object[] a, Object b){{ int n=a.length;int n=a.length; for (int i=0; i<n; i++)for (int i=0; i<n; i++) {{ if (a[i].equals(b))if (a[i].equals(b)) return i;return i; }} return –1;return –1;}}

}}

Page 38: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

public classpublic class StudentTest StudentTest{{

public static void main(String[] args)public static void main(String[] args){{ Student[] s = new Student[3];Student[] s = new Student[3];

s[0]=new Student(“John Smith”, 3429, s[0]=new Student(“John Smith”, 3429, ““21 Bristol Rd”);21 Bristol Rd”);

s[1]=new Student(“Paul Evans”, 5393, s[1]=new Student(“Paul Evans”, 5393, ““9 Pershore Rd”);9 Pershore Rd”);

s[2]=new Student(“John Smith”, 6592,s[2]=new Student(“John Smith”, 6592,““3 Dawlish Rd”);3 Dawlish Rd”);

Student st=new Student(“SmithJ”,6592, “5 Dawlish Rd”);Student st=new Student(“SmithJ”,6592, “5 Dawlish Rd”); int index=SearchAlg.linearSearch(s,st);int index=SearchAlg.linearSearch(s,st); System.out.println(“Student found at index ” + index)System.out.println(“Student found at index ” + index)}}

}}

Page 39: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

Key point is that Key point is that SearchAlg.linearSearch() SearchAlg.linearSearch() works works for for anyany type of object passed to it as long as an type of object passed to it as long as an equals()equals() method is defined for the object method is defined for the object The cast from object to The cast from object to Student Student is crucial in is crucial in

enabling polymorphism to workenabling polymorphism to work

The argument to the The argument to the equals()equals() method must be method must be an an Object Object for it to be overidden with the for it to be overidden with the equals()equals() method in method in StudentStudent

Page 40: EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope

And finally…..

This has been an important lecture in This has been an important lecture in explaining the mechanics and some simple explaining the mechanics and some simple examples of inheritance and polymorphismexamples of inheritance and polymorphism

Its important to understand why Its important to understand why polymorphism is key to object oriented polymorphism is key to object oriented programmingprogramming

You will develop a fuller understanding of You will develop a fuller understanding of this from the EE2E2 (object oriented design) this from the EE2E2 (object oriented design) coursecourse


Top Related