Saturday 3 August 2013

21:Inheritance, Interfaces and Abstract Classes

Learning Objectives
After completing this session, you will be able to:
‰  Define Inheritance
‰  Explain the need of Inheritance
‰  Identify how to derive a subclass
‰  Define Object class
‰  Explain constructor calling chain
‰  Identify “super” keyword
‰  Override methods
‰  Hide methods and fields
‰  Apply type casting
‰  Write final class and final methods
Inheritance
‰  Inheritance is the concept of a child class (sub class) automatically inheriting the
variables and methods defined in its parent class (super class).
‰  The primary features of object-oriented programming are encapsulation and
polymorphism.
Importance of Inheritance
‰  The benefit of inheritance in OOP is reusability. Once a behavior (method) is defined
in a super class, that behavior is automatically inherited by all subclasses
‰  Thus, you write a method only once and it can be used by all subclasses:
‰  Once a set of properties (fields) are defined in a super class, the same set of
properties are inherited by all subclasses. A class and its children share common set
of properties
‰  A subclass only needs to implement the differences between itself and the parent.
Deriving a Subclass
‰  To derive a child class, you use the extendskeyword.
‰  Suppose you 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 = "";
}
. . . .
}
extends Keyword
‰  Now, you want to create another class named Student.
‰  Since a student is also a person, you decide to just extend the class Person, so that
you can inherit all the properties and methods of the existing class Person.
‰  To do this, you write,
public class Student extends Person {
public Student(){
System.out.println(“Inside Student:Constructor”);
}
. . . .
}
What you can do in a Subclass
‰  A subclass inherits all of the “public” and “protected” members (fields or methods) of
its parent, no matter what package the subclass is in.
‰  If the subclass is in the same package as its parent, then it also inherits the packageprivate members (fields or methods) of the parent.
What you can do in a Sub-class Regarding Fields
‰  The inherited fields can be used directly, just like any other fields.
‰  You can declare new fields in the subclass that are not in the super class.
‰  You can declare a field in the subclass with the same name as the one in the super
class, thus hiding it (not recommended).
‰  A subclass does not inherit the private members of its parent class. However, if the
super class has public or protected methods for accessing its private fields, these can
also be applied by the subclass.
What you can do in a Sub-class Regarding Methods
‰  The inherited methods can be used directly as they are.
‰  You can write a new instance method in the subclass that has the same signature as
the one in the super class, thus overriding it.
‰  You can write a new static method in the subclass that has the same signature as the
one in the super class, thus hiding it.
‰  You can declare new methods in the subclass that are not in the super class.
Object Class
Object class is mother of all classes.
In Java language, all classes are subclassed (extended) from the Object super class.
Object class is the only class that does not have a parent class
Object class defines and implements behavior common to all classes including the ones that you
write.
Following are some of the importantmethods of the Object class:
‰  getClass()
‰  equals()
‰  toString()
Class Hierarchy
A sample class hierarchy is shown in the following figure:
Superclass and Subclass
‰  Superclass (Parent class) :Any class preceding a specific class in the class
hierarchy
‰  Sub class (Child class) :Any class following a specific class in the class hierarchy
How Constructor Method of a Super Class gets Called
‰  A subclass constructor invokes the constructor of the superclass implicitly. When a
Student object, a subclass (child class), is instantiated, the default constructor of its
super class (parent class), Person class, isinvoked implicitly before the constructor
method of the subclass is invoked.
‰  A subclass constructor can invoke the constructor of the super explicitly by using the
“super” keyword:
‰  The constructor of the Student class can explicitly invoke the constructor of the Person
class using “super” keyword
‰  Used when passing parameters to the constructor of the super class
Example: Constructor Calling Chain
To illustrate this, consider the following code:
public static void main( String[] args ){
Student anna = new Student();
}
In the code, you create an object of class Student.
The output of the program is:
Inside Person:Constructor
Inside Student:Constructor
Example: Constructor Calling Chain
The program flow is shown in the following figure:
The “super” Keyword
‰  A subclass can also explicitly call a constructor of its immediate super class.
‰  This is done by using the super constructor call.
‰  A super constructor call in the constructor of a subclass will result in the execution of
relevant constructor from the super class, based on the arguments passed.
‰  For example, in your preceding example classes Person and Student, you show an
example of a super constructor call.
‰  In the given the following code for Student:
public Student(){
super( "SomeName", "SomeAddress" );
System.out.println("Inside Student:Constructor");
}
Few things to remember when using the super constructor call:
‰  The super() call must occur as the first statement in a constructor.
‰  The super() call can only be used in a constructor (not in ordinary methods).
Another use of super is to refer to members of the super class (just like the this reference ).
For example:
public Student() {
super.name = “somename”;
super.address = “some address”;
}
Overriding Methods
‰  If a derived class needs to have a differentimplementation of a certain instance
method from that of the super class, thenoverride that instance method in the sub
class:
‰  Note that the scheme of overriding applies only to instance methods.
‰  For static methods, it is called hiding methods.
‰  The overriding method has the same name, number and type of parameters, and
return type as the method it overrides.
‰  The overriding method can also return a subtype of the type returned by the
overridden method This is called a covariant return type.
Example: Overriding Methods
Suppose you have the following implementation for the getNamemethod in the Personsuper
class:
public class Person {
:
:
public String getName(){
System.out.println("Parent: getName");
return name;
}
}
To override the getName() method of the superclass Person in the subclass Student, reimplement
the method with the same signature.
public class Student extends Person{
:
public String getName(){
System.out.println("Student: getName");
return name;
}
:
}
Now, when you invoke the getName() method of an object of the subclass Student, the getName()
method of the Student class would be called, and the output would be:
Student: getName
Modifiers in the Overriding Methods
‰  The access specifier for an overriding method can allow more, but not less, access
than the overridden method. For example, a protected instance method in the super
class can be made public, but not private, in the subclass.
‰  You will get a compile-time error if you attempt to change an instance method in the
super class to a class method in the subclass, or change the class method to an
instance method in the super class.
Run-time Polymorphism with Overriding Methods
Polymorphism in a Java program means:
‰  The ability of a reference variable to change behavior according to what object
instance it is holding
‰  This allows multiple objects of different subclasses to be treated as objects of a single
super class, while automatically selecting the proper methods to apply to a particular
object based on the subclass it belongs to
Example: Run-time Polymorphism
Code:
Person person2 = new Student();
person2.myMethod("test4");
Person person3 = new InternationalStudent();
person3.myMethod("test5");
Result:
myMethod(test4) in Student class is called
myMethod(test5) in InternationalStudent class is called.
Hiding Methods
If a subclass defines a class method (static method) with the same signature as a class method in
the super class, then the method in the subclass “hides” the one in the super class.
Example: Coding of Hiding Static Method
class Animal {
public static void testClassMethod() {
System.out.println("The class method in Animal.");
}
}
// The testClassMethod() of the child class hides the one of
// the super class – it looks like overriding, doesn't it?
class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The class method in Cat.");
}
}
Overriding Method Versus Hiding Method
Hiding a static method of a super class looks like overriding an instance method of a super class.
The difference comes during run time:
‰  When you override an instance method, you getthe benefit of run-time polymorphism.
‰  When you override a static method, there is no runt-time polymorphism.
Example: Overriding Method Versus Hiding Method During Runtime
// Create object instance of Cat.
Cat myCat = new Cat();
// The object instance is Cat type
// and assigned to Animal type variable.
Animal myAnimal2 = myCat;
// For static method, the static method of
// the super class gets called.
Animal.testClassMethod();
// For instance method, the instance method
// of the subclass is called even though
// myAnimal2 is a super class type. This is
// run-time polymorphism.
myAnimal2.testInstanceMethod();
Hiding Fields
‰  Within a sub class, a field that has the samename as a field in the super class, hides
the super class' field, even if their types are different.
‰  Within the subclass, the field in the super class cannot be referenced by its simple
name, instead, the field must be accessed through super keyword.
‰  Generally speaking, hiding fields is not a recommended programming practice as it
makes code difficult to read.

No comments:

Post a Comment