MELJUN CORTES JEDI course notes intro1-lesson11-inheritance, polymorphism and interfaces


Published on

MELJUN CORTES JEDI course notes intro1-lesson11-inheritance, polymorphism and interfaces

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

MELJUN CORTES JEDI course notes intro1-lesson11-inheritance, polymorphism and interfaces

  1. 1. J.E.D.I. Inheritance, Polymorphism and Interfaces1 ObjectivesIn this section, we will be discussing on how a class can inherit the properties of anexisting class. A class that does this is called a subclass and its parent class is called thesuperclass. We will also be discussing a special property of Java wherein it canautomatically apply the proper methods to each object regardless of what subclass theobject came from. This property is known as polymorphism. Finally, we are going todiscusss about interfaces that helps reduce programming effort.At the end of the lesson, the student should be able to: • Define super classes and subclasses • Override methods of superclasses • Create final methods and final classes2 InheritanceIn Java, all classes, including the classes that make up the Java API, are subclassed fromthe Object superclass. A sample class hierarchy is shown below.Any class above a specific class in the class hierarchy is known as a superclass. Whileany class below a specific class in the class hierarchy is known as a subclass of thatclass. Figure 1: Class HierarchyInheritance is a major advantage in object-oriented programming since once a behavior(method) is defined in a superclass, that behavior is automatically inherited by allsubclasses. Thus, you can encode a method only once and they can be used by allsubclasses. A subclass only need to implement the differences between itself and theparent.Introduction to Programming I 1
  2. 2. J.E.D.I.2.1 Defining Superclasses and SubclassesTo derive a class, we use the extends keyword. In order to illustrate this, lets create asample parent class. Suppose we have a parent class called Person. public class Person { protected String name; protected String address; /** * Default constructor */ public Person(){ System.out.println(“Inside Person:Constructor”); name = ""; address = ""; } /** * Constructor with 2 parameters */ public Person( String name, String address ){ = name; this.address = address; } /** * Accessor methods */ public String getName(){ return name; } public String getAddress(){ return address; } public void setName( String name ){ = name; } public void setAddress( String add ){ this.address = add; } }Notice that, the attributes name and address are declared as protected. The reason wedid this is that, we want these attributes to be accessible by the subclasses of thesuperclass. If we declare this as private, the subclasses wont be able to use them. Takenote that all the properties of a superclass that are declared as public, protected anddefault can be accessed by its subclasses.Introduction to Programming I 2
  3. 3. J.E.D.I.Now, we want to create another class named Student. Since a student is also a person,we decide to just extend the class Person, so that we can inherit all the properties andmethods of the existing class Person. To do this, we write, public class Student extends Person { public Student(){ System.out.println(“Inside Student:Constructor”); //some code here } // some code here }When a Student object is instantiated, the default constructor of its superclass is invokedimplicitly to do the necessary initializations. After that, the statements inside thesubclass are executed. To illustrate this, consider the following code, public static void main( String[] args ){ Student anna = new Student(); }In the code, we create an object of class Student. The output of the program is, Inside Person:Constructor Inside Student:ConstructorThe program flow is shown below. Figure 2: Program FlowIntroduction to Programming I 3
  4. 4. J.E.D.I.2.2 The super keywordA subclass can also explicitly call a constructor of its immediate superclass. This is doneby using the super constructor call. A super constructor call in the constructor of asubclass will result in the execution of relevant constructor from the superclass, based onthe arguments passed.For example, given our previous example classes Person and Student, we show anexample of a super constructor call. Given the following code for Student, public Student(){ super( "SomeName", "SomeAddress" ); System.out.println("Inside Student:Constructor"); }This code calls the second constructor of its immediate superclass (which is Person) andexecutes it. Another sample code shown below, public Student(){ super(); System.out.println("Inside Student:Constructor"); }This code calls the default constructor of its immediate superclass (which is Person) andexecutes it.There are a few things to remember when using the super constructor call:1. The super() call MUST OCCUR THE FIRST STATEMENT IN A CONSTRUCTOR.2. The super() call can only be used in a constructor definition.3. This implies that the this() construct and the super() calls CANNOT BOTH OCCUR IN THE SAME CONSTRUCTOR.Another use of super is to refer to members of the superclass (just like the thisreference ). For example, public Student() { = “somename”; super.address = “some address”; }Introduction to Programming I 4
  5. 5. J.E.D.I.2.3 Overriding MethodsIf for some reason a derived class needs to have a different implementation of a certainmethod from that of the superclass, overriding methods could prove to be very useful.A subclass can override a method defined in its superclass by providing a newimplementation for that method.Suppose we have the following implementation for the getName method in the Personsuperclass, public class Person { : : public String getName(){ System.out.println("Parent: getName"); return name; } : }To override, the getName method in the subclass Student, we write, public class Student extends Person { : : public String getName(){ System.out.println("Student: getName"); return name; } : }So, when we invoke the getName method of an object of class Student, the overriddenmethod would be called, and the output would be, Student: getNameIntroduction to Programming I 5
  6. 6. J.E.D.I.2.4 Final Methods and Final ClassesIn Java, it is also possible to declare classes that can no longer be subclassed. Theseclasses are called final classes. To declare a class to be final, we just add the finalkeyword in the class declaration. For example, if we want the class Person to be declaredfinal, we write, public final class Person { //some code here }Many of the classes in the Java API are declared final to ensure that their behaviorcannot be overridden. Examples of these classes are Integer, Double and String.It is also possible in Java to create methods that cannot be overridden. These methodsare what we call final methods. To declare a method to be final, we just add the finalkeyword in the method declaration. For example, if we want the getName method inclass Person to be declared final, we write, public final String getName(){ return name; }Static methods are automatically final. This means that you cannot override them.Introduction to Programming I 6
  7. 7. J.E.D.I.3 PolymorphismNow, given the parent class Person and the subclass Student of our previous example,we add another subclass of Person which is Employee. Below is the class hierarchy forthat, Person Student Employee Figure 3: Hierarchy for Person class and its classesIn Java, we can create a reference that is of type superclass to an object of its subclass.For example, public static main( String[] args ) { Person ref; Student studentObject = new Student(); Employee employeeObject = new Employee(); ref = studentObject; //Person ref points to a // Student object //some code here }Now suppose we have a getName method in our superclass Person, and we override thismethod in both the subclasses Student and Employee, public class Person { public String getName(){ System.out.println(“Person Name:” + name); return name; } } public class Student extends Person { public String getName(){ System.out.println(“Student Name:” + name); return name; } } public class Employee extends Person { public String getName(){ System.out.println(“Employee Name:” + name); return name; } }Introduction to Programming I 7
  8. 8. J.E.D.I.Introduction to Programming I 8
  9. 9. J.E.D.I.Going back to our main method, when we try to call the getName method of thereference Person ref, the getName method of the Student object will be called. Now, ifwe assign ref to an Employee object, the getName method of Employee will be called. public static main( String[] args ) { Person ref; Student studentObject = new Student(); Employee employeeObject = new Employee(); ref = studentObject; //Person reference points to a // Student object String temp = ref.getName(); //getName of Student //class is called System.out.println( temp ); ref = employeeObject; //Person reference points to an // Employee object String temp = ref.getName(); //getName of Employee //class is called System.out.println( temp ); }This ability of our reference to change behavior according to what object it is holding iscalled polymorphism. Polymorphism allows multiple objects of different subclasses tobe treated as objects of a single superclass, while automatically selecting the propermethods to apply to a particular object based on the subclass it belongs to.Another example that exhibits the property of polymorphism is when we try to pass areference to methods. Suppose we have a static method printInformation that takes ina Person object as reference, we can actually pass a reference of type Employee and typeStudent to this method as long as it is a subclass of the class Person. public static main( String[] args ) { Student studentObject = new Student(); Employee employeeObject = new Employee(); printInformation( studentObject ); printInformation( employeeObject ); } public static printInformation( Person p ){ . . . . }Introduction to Programming I 9
  10. 10. J.E.D.I.4 Abstract ClassesNow suppose we want to create a superclass wherein it has certain methods in it thatcontains some implementation, and some methods wherein we just want to beoverridden by its subclasses.For example, we want to create a superclass named LivingThing. This class has certainmethods like breath, eat, sleep and walk. However, there are some methods in thissuperclass wherein we cannot generalize the behavior. Take for example, the walkmethod. Not all living things walk the same way. Take the humans for instance, wehumans walk on two legs, while other living things like dogs walk on four legs. However,there are many characteristics that living things have in common, that is why we want tocreate a general superclass for this. Figure 4: Abstract classIn order to do this, we can create a superclass that has some methods withimplementations and others which do not. This kind of class is called an abstract class.An abstract class is a class that cannot be instantiated. It often appears at the top ofan object-oriented programming class hierarchy, defining the broad types of actionspossible with objects of all subclasses of the class.Those methods in the abstract classes that do not have implementation are calledabstract methods. To create an abstract method, just write the method declarationwithout the body and use the abstract keyword. For example, public abstract void someMethod();Introduction to Programming I 10
  11. 11. J.E.D.I.Now, lets create an example abstract class. public abstract class LivingThing { public void breath(){ System.out.println("Living Thing breathing..."); } public void eat(){ System.out.println("Living Thing eating..."); } /** * abstract method walk * We want this method to be overridden by subclasses of * LivingThing */ public abstract void walk(); }When a class extends the LivingThing abstract class, it is required to override theabstract method walk(), or else, that subclass will also become an abstract class, andtherefore cannot be instantiated. For example, public class Human extends LivingThing { public void walk(){ System.out.println("Human walks..."); } }If the class Human does not override the walk method, we would encounter the followingerror message, Human is not abstract and does not override abstract method walk() in LivingThing public class Human extends LivingThing ^ 1 errorCoding Guidelines:Use abstract classes to define broad types of behaviors at the top of an object-orientedprogramming class hierarchy, and use its subclasses to provide implementation detailsof the abstract class.Introduction to Programming I 11
  12. 12. J.E.D.I.5 InterfacesAn interface is a special kind of block containing method signatures (and possiblyconstants) only. Interfaces define the signatures of a set of methods without the body.Interfaces define a standard and public way of specifying the behavior of classes. Theyallow classes, regardless of their location in the class hierarchy, to implement commonbehaviors. Note that interfaces exhibit polymorphism as well, since program may call aninterface method and the proper version of that method will be executed depending onthe type of object passed to the interface method call.5.1 Why do we use Interfaces?We need to use interfaces if we want unrelated classes to implement similar methods.Thru interfaces, we can actually capture similarities among unrelated classes withoutartificially forcing a class relationship.Lets take as an example a class Line which contains methods that computes the lengthof the line and compares a Line object to objects of the same class. Now, suppose wehave another class MyInteger which contains methods that compares a MyIntegerobject to objects of the same class. As we can see here, both of the classes have somesimilar methods which compares them from other objects of the same type, but they arenot related whatsoever. In order to enforce a way to make sure that these two classesimplement some methods with similar signatures, we can use an interface for this. Wecan create an interface class, lets say interface Relation which has some comparisonmethod declarations. Our interface Relation can be declared as, public interface Relation { public boolean isGreater( Object a, Object b); public boolean isLess( Object a, Object b); public boolean isEqual( Object a, Object b); }Another reason for using an objects programming interface is to reveal an objectsprogramming interface without revealing its class. As we can see later on the sectionInterface vs. Classes, we can actually use an interface as data type.Finally, we need to use interfaces to model multiple inheritance which allows a class tohave more than one superclass. Multiple inheritance is not present in Java, but presentin other object-oriented languages like C++.5.2 Interface vs. Abstract ClassThe following are the main differences between an interface and an abstract class:interface methods have no body, an interface can only define constants and an interfacehave no direct inherited relationship with any particular class, they are definedindependently.Introduction to Programming I 12
  13. 13. J.E.D.I.5.3 Interface vs. ClassOne common characteristic of an interface and class is that they are both types. Thismeans that an interface can be used in places where a class can be used. For example,given a class Person and an interface PersonInterface, the following declarations arevalid: PersonInterface pi = new Person(); Person pc = new Person();However, you cannot create an instance from an interface. An example of this is: PersonInterface pi = new PersonInterface(); //COMPILE //ERROR!!!Another common characteristic is that both interface and class can define methods.However, an interface does not have an implementation code while the class have one.5.4 Creating InterfacesTo create an interface, we write, public interface [InterfaceName] { //some methods without the body }As an example, lets create an interface that defines relationships between two objectsaccording to the “natural order” of the objects. public interface Relation { public boolean isGreater( Object a, Object b); public boolean isLess( Object a, Object b); public boolean isEqual( Object a, Object b); }Now, to use the interface, we use the implements keyword. For example, /** * This class defines a line segment */ public class Line implements Relation { private double x1; private double x2; private double y1; private double y2; public Line(double x1, double x2, double y1, double y2){ this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; }Introduction to Programming I 13
  14. 14. J.E.D.I. public double getLength(){ double length = Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)* (y2-y1)); return length; } public boolean isGreater( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen > bLen); } public boolean isLess( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen < bLen); } public boolean isEqual( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen == bLen); } }When your class tries to implement an interface, always make sure that you implementall the methods of that interface, or else, you would encounter this error, Line is not abstract and does not override abstract method isGreater(java.lang.Object,java.lang.Object) in Relation public class Line implements Relation ^ 1 errorCoding Guidelines:Use interfaces to create the same standard method definitions in may different classes.Once a set of standard method definition is created, you can write a single method tomanipulate all of the classes that implement the interface.Introduction to Programming I 14
  15. 15. J.E.D.I.5.5 Relationship of an Interface to a ClassAs we have seen in the previous section, a class can implement an interface as long as itprovides the implementation code for all the methods defined in the interface.Another thing to note about the relationship of interfaces to classes is that, a class canonly EXTEND ONE super class, but it can IMPLEMENT MANY interfaces. An example of aclass that implements many interfaces is, public class Person implements PersonInterface, LivingThing, WhateverInterface { //some code here }Another example of a class that extends one super class and implements an interface is, public class ComputerScienceStudent extends Student implements PersonInterface, LivingThing { //some code here }Take note that an interface is not part of the class inheritance hierarchy. Unrelatedclasses can implement the same interface.5.6 Inheritance among InterfacesInterfaces are not part of the class hierarchy. However, interfaces can have inheritancerelationship among themselves. For example, suppose we have two interfacesStudentInterface and PersonInterface. If StudentInterface extends PersonInterface,it will inherit all of the method declarations in PersonInterface. public interface PersonInterface { . . . } public interface StudentInterface extends PersonInterface { . . . }Introduction to Programming I 15
  16. 16. J.E.D.I.6 Exercises6.1 Extending StudentRecordIn this exercise, we want to create a more specialized student record that containsadditional information about a Computer Science student. Your task is to extend theStudentRecord class that was implemented in the previous lessons. Add some attributesand methods that you think are needed for a Computer Science student record. Try tooverride some existing methods in the superclass StudentRecord, if you really need to.6.2 The Shape abstract classTry to create an abstract class called Shape with abstract methods getArea() andgetName(). Write two of its subclasses Circle and Square. You can add additionalmethods to its subclasses if you want to.Introduction to Programming I 16