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

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

Post on 05-Jan-2016

217 views

Category:

Documents

1 download

Embed Size (px)

TRANSCRIPT

<ul><li><p>EE2E1. JAVA Programming</p><p>Lecture 3</p><p>Inheritance</p></li><li><p>ContentsBase classes and derived classesProtected scope Inheritance hierarchiesThe IS-A relationshipPolymorphismAbstract classesSuperclass Object</p></li><li><p>Base classes and derived classesInheritance is a fundamental requirement for object orientationInheritance allows new classes to be derived from existing classesExisting methods can be changed and extra instance fields can be added in the derived class</p></li><li><p>ExampleA Student class represents basic information about students at the UniversityThere are many categories of studentsWe can think about extending the Student class to representUndergraduate studentsPostgraduate studentsEach extension requires additional instance fields</p></li><li><p>class UndergradStudent represents the basic student informationnameid. numberaddressIt also represents undergraduate specific informationdegree programme</p></li><li><p>Likewise class PostgradStudent represents the basic student informationnameid. numberaddressIt also represents postgraduate specific informationresearch supervisor</p></li><li><p>public class Student{public Student(String n, int id, String a){ name=new String(n); idNumber=id; address=new String(a);}</p><p>public void printInfo(){ System.out.println(name + + idNumber + + address);}</p><p>private String name;private int idNumber;private String address;}</p></li><li><p>public class UndergradStudent extends Student{public UndergradStudent(String n, int id, String a, String d){ super(n,id,a); degreeProgramme=new String(d);}</p><p>public void printInfo(){ super.printInfo(); System.out.println(degreeProgramme);}</p><p>private String degreeProgramme;}</p></li><li><p>public class PostgradStudent extends Student{public PostgradStudent(String n, int id, String a, String p){ super(n,id,a); projectSupervisor=new String(p);}</p><p>public void printInfo(){ super.printInfo(); System.out.println(projectSupervisor);}</p><p>private String projectSupervisor;}</p></li><li><p>public class StudentTest{public static void main(String[] args){ UndergradStudent s1=new UndergradStudent(John Smith, 3429, 21 Bristol Rd, Electrical Eng);</p><p> PostgradStudent s2=new PostgradStudent(Alan Jones, 5395, 30 Bournbrook Rd,Dr. Mike Spann); </p><p> s1. printInfo();</p><p> s2.printInfo();}}</p></li><li><p>Keyword extends means we are making a new class which derives from an existing classThe new class is the derived class and the existing class is the base classStudent is the base classClasses PostgradStudent and UndergradStudent are derived classesAlso the terms superclass (base class) and subclass (derived class) are often used</p></li><li><p>A key point is that private instance fields in the base class cannot be accessed by derived class methodsThe derived class constructor invokes the base class constructor through the call to super()Must be the first statement in the derived class constructorAvoids the derived class having to access private instance fields in order to initialize them</p></li><li><p>Protected scope Protected scope gives a derived class access to base class instance fields and methods declared as protectedBreaks encapsulation only in the inheritance hierarchy</p></li><li><p>class myClass{..protected int member;}class anotherClass extends myClass{public f() { member=1;// OK member protected}..}</p></li><li><p>Summary of member scope</p><p>ScopeKeywordVisible (where)?PrivateprivateIn encapsulating classProtectedprotectedIn encapsulating classs derived classes or packagePublicpublicWherever the encapsulating class is visible</p></li><li><p>Inheritance hierarchiesA simple tree diagram indicates the base class/derived class relationship</p></li><li><p>The hierarchy can easily be extended</p></li><li><p>The IS-A relationshipAny object that is an instance of a derived class must be useable in place of an object which is an instance of a base classBase class/derived class relationship form an IS-A relationshipPostgradStudent IS-A StudentMastersStudent IS-A PostgradStudent etc</p></li><li><p>We can assign a derived class object to a base class variableBecomes important for polymorphismThe converse is not legal we cant assign a base class object to a derived class variableCan use a cast but be careful!</p></li><li><p>public class StudentTest{public static void main(String[] args){Student[] s=new Student[2];</p><p>PostgradStudent ps=new PostgradStudent( Alan Jones, 5395, 30 Bournbrook Rd,Dr. Mike Spann); </p><p>UndergradStudent us=new UndergradStudent(John Smith, 3429, 21 Bristol Rd, Electrical Eng);</p><p>s[0]=ps; // legal assignments[1]=us;// legal assignment</p><p>ps=s[0];// Error! }} </p></li><li><p>PolymorphismCrucial to object oriented programmingIt is an object determining which method to call depending on where it is in the inheritance hierarchyWhile the method (argument and return types) might be the same, objects might respond differently </p></li><li><p>When a method of a derived class is called through a reference to a base class objectThe derived class method is called if there is a match (argument types and return type)Otherwise the method call is passed to the base class (or to the next class up the inheritance hierarchy)The key is late binding. Code for the method call is generated at runtime</p></li><li><p>public class Student{..</p><p>public void displayFees(){}</p><p>.</p><p>}</p></li><li><p>public class UndergradStudent extends Student{..</p><p>public void displayFees(){ System.out.println(Undergrad. fees are 1000 pounds);}</p><p>.</p><p>}</p></li><li><p>public class PostgradStudent extends Student{..</p><p>public void displayFees(){ System.out.println(Postgrad. fees are 5000 pounds);}</p><p>.</p><p>}</p></li><li><p>public class StudentTest{public static void main(String[] args){Student[] s=new Student[2];</p><p>PostgradStudent ps=new PostgradStudent( Alan Jones, 5395, 30 Bournbrook Road,Dr. Mike Spann); </p><p>UndergradStudent us=new UndergradStudent(John Smith, 3429, 21 Bristol Road, Electrical Eng);</p><p>s[0]=ps; // legal assignments[1]=us;// legal assignment</p><p>s[0].displayFees();// Postgraduate fees displayeds[1].displayFees();// Undergraduate fees displayed}}</p></li><li><p>Method displayFees() exhibits different functionality depending on the object making the callNo obvious implementation of Student.displayFees() method could make it abstract (see next section)However if a displayFees() method is not present in the derived class, the call is passed up to the base classMethod calls are always passed up the inheritance chain until a match is found</p></li><li><p>So why the big deal over polymorphism?Easy to extend the hierarchySimply add displayFees() methods for new classes in the hierarchyExisting code will still work!Student s=new Student();</p><p>MastersStudent ms=new MastersStudent(); s=ms; // legal assignment</p><p>s.displayFees();// Masters student fees displayed</p></li><li><p>Abstract classesAt high levels in the inheritance hierarchy, classes become more and more abstractThe implementation of their methods becomes less clear and more abstractA call to an abstract method is always delegated down to one of the derived class methodsA class containing at least one abstract method is called an abstract classJava uses the keyword abstract to denote abstract classes and methods</p></li><li><p>public abstract class Shape{public Shape(int x, int y){xpos=x; ypos=y;}public void move(int dx, int dy){xpos+=dx; ypos+=dy;}</p><p>public abstract float area();</p><p>private int xpos, ypos;}public class Square extends Shape{public Square(int x, int y, int s){super(x,y); side=s;}public float area() {return side*side;}</p><p>private int side;}</p></li><li><p>The method area() is abstract which makes the class Shape abstractA Shape object cannot be created</p><p>Shape s = new Shape(0,0);// Error!We can have Shape object variables but they must refer to a derived class objectShape sq = new Square(0,0,100);// OKfloat a = sq.area();The method move() is non-abstract and is not overridden in the derived classesCommon functionality across the inheritance hierarchy</p></li><li><p>Superclass ObjectClass Object is the ultimate ancestor of every class in Java However, we dont have to explicitly write</p><p>class myClass extends Object Useful for generic programmingAlternative is C++ template classes which are more complex</p></li><li><p>Example a generic search algorithmWe want a generic search algorithm to search for any kind of object in an arrayClass Object provides an equals() method to test whether one object is equal to anotherSimply checks if the 2 object references point to the same area of memoryNot very useful in practice!We need to provide an equals() method in the class of the object we are searching forPolymorphism does the rest!</p></li><li><p>In the following example we are searching for a Student object in an array The search is based on the student ID numberClass SearchAlg provides a linearSearch method which carries out the searchWe have provided an implementation of equals() in class Student</p></li><li><p>public class Student{public Student(String n, int id, String a){ name=n; idNumber=id; address=a;}</p><p>public boolean equals(Object obj){ Student s = (Student) obj; return (idNumber==s.idNumber);}</p><p>private String name;private int idNumber;private String address;}</p></li><li>public class SearchAlg{public static int linearSearch(Object[] a, Object b){ int n=a.length; for (int i=0; i</li><li><p>public class StudentTest{public static void main(String[] args){ Student[] s = new Student[3];</p><p> s[0]=new Student(John Smith, 3429, 21 Bristol Rd); s[1]=new Student(Paul Evans, 5393, 9 Pershore Rd); s[2]=new Student(John Smith, 6592,3 Dawlish Rd);</p><p> Student st=new Student(SmithJ,6592, 5 Dawlish Rd); int index=SearchAlg.linearSearch(s,st); System.out.println(Student found at index + index)}}</p></li><li><p>Key point is that SearchAlg.linearSearch() works for any type of object passed to it as long as an equals() method is defined for the objectThe cast from object to Student is crucial in enabling polymorphism to workThe argument to the equals() method must be an Object for it to be overidden with the equals() method in Student</p></li><li><p>And finally..This has been an important lecture in explaining the mechanics and some simple examples of inheritance and polymorphismIts important to understand why polymorphism is key to object oriented programmingYou will develop a fuller understanding of this from the EE2E2 (object oriented design) course</p></li></ul>

Recommended

View more >