Inheritance
Lectures 20-21
- Basis of Inheritance is commonality of behaviour (and structure).
- Base class “Object”
- Every ‘User defined Type’ is an extension of the class Object in Java.
- Methods of class Object
- GetClass – return the Class object representing class of the object
- ToString – returns string representation of object
- equals – default object ‘structural Value’ equality obj1.equals(obj2)
- (not reference/pointer equality ==)
- hashCode
- Clone – makes a duplicate of an object
- wait, notify, notifyAll – used with concurrency
- finalize
- Inheritance for Specialization
- Derived class is more specialised class of base class.
- It has a ISA relationship or HAS a relationship.
- ISA relationship:
- Derived class ISA Special case of the Base Class.
- EX1: Filled circle is special case of Circle
class Circle {
Circle(){. . .}
Circle(int radii) {. . .}
protected void draw() {…}
protected void rotate(int ang){}
}
class FilledCircle extends Circle {
FilledCircle() {…}
FilledCircle(int radii) {
super(i);
… }
protected void draw() {…}
protected void rotate(int ang){...}
}
- Commonality of behaviour is basis of ISA relationship.
- Commonality does not come into HAS a relationship. Derived class is associated or related or dependent on base class.
- EX: I am associated to IIT Kanpur or Chair has 4 legs
- Inheritance is simple because for every base class we can substitute derived class. e.g.
Shape S; Circle C;
S=C;
S.draw();
- Inheritance for Specification: Consider below example -
class Shape {
Shape();
Shape(int dist);
protected void draw();
protected void rotate(int angle);
}
class Circle extends Shape {
Circle() {. . .}
Circle(int radii) {
super(i); … }
protected void draw() {…}
protected void rotate(int angle){}
}
- We cannot implement any constructor or method of the class ‘Shape’ as we do not have any structural or behavioral details to implement Shape.
- Yet the class Shape is of great value, it gives abstraction of the Shape class and all it subclasses.
- Suppose we are given different types of geometric shapes like circle, triangle, square, rectangle … and want to make a display / rendering SW system to draw and calcArea.
- In C: We require to make different structures for each shape and independent set of operations for each structure. Though structure and its implimentation are different the operations are same. We can go one stage up and make shapeless class Shape with no structure or implementation. We can collaborate through parameters of operation which makes objects dependent and highly coupled.
- Language that do not support ISA convert ISA to HAS a relationship.
- In Java , we use inheritance for Specification either by using Abstract class or Interface
- Inheritance for Specification : Abstract Class
- At least one method must be Abstract method, it does not have an implementation.
- Any class that has an abstract method in it or that does not provide an implementation for any abstract method declared in its superclasses must be declared as an abstract class.
- Abstract class, is a class that cannot be instantiated.
- Java supports both Abstract class and Interface.
- Inheritance for Specification : Interface
- Helps defining a usage contract between classes. Reveals an object's programming interface without revealing its class. Captures similarities among unrelated classes without artificially forcing a class relationship.
- Declares methods that one or more classes are expected to implement.
- Facilitates multiple inheritance in Java by inheriting many interfaces.
- Perfect tool for encapsulating classes inner structure. Only the
- interface is exposed.
- No method can be implemented. C++ does not support.
- Abstract Class vs. Interface
- Both captures abstraction (basis for commonality of abstraction),
- None can be instantiated,
- An interface can be extended from multiple interfaces.
- Abstract class may have some implementations, interface don’t have any,
- Interfaces may contain static final variables (constt).
- Java permits to inherit a single class, and multiple interfaces.
- It is a Design Issue to use an abstract Class / Concrete Class or Interface.
- Subclasses, Substitution & Subtypes
- An inherited class is a subclass. OOP (implicitly) assumes that subclasses are subtypes. In Type substitution an instance of a subclass can be assigned to a variable declared as the parent class type.
- Not all subclasses formed using inheritance are candidates for substitution i.e Subclasses are subtypes, is not always valid.
- Creating subclasses that are not subtypes, may lead to error.For proper reusability every subclass must be subtype.
- We can do explicit use of RTTIs. (Run Time Type Identification) using
- Dynamic Cast
- instance of Operator
- But RTTIs are counter to Reusability.Therefore good programmers do not use it.In Object oriented computing there is no need to know the dynamic type, thus don’t give RTTI to programmer.
- Liskov Substitution Principle (LSP)
- Sub-classes are constructed using inheritance.
- Declaration of a variable may not match the type associated
- with a value the variable is holding.
- Shape S = new Circle ();
- If following 3 Validity of Substitutability happen then there is no need of RTTI:
- Instance of the subclass must possess all data associated with the parent class.
- Instance of the subclass must implement, through inheritance at least (if not explicitly overridden) all functionality defined for the parent class. (They may define new functionality, but that is unimportant for the argument.)
- Thus, an instance of a child class can mimic the behavior of the parent class and should be indistinguishable from an instance of the parent class if substituted in a similar fashion.
- Object oriented first principle is Every subclass is subtype. Avoid Inheritance in which above assumption does not hold.
- The term subtype is used to describe the relationship between types that explicitly recognizes the principle of substitution.
- A type B is considered to be a subtype of A, if the following two conditions hold:
- 1. An instance of B can legally be assigned to a variable declared as type A. e,g,: A = B;
- 2. The value can then be used by the variable with no observable change in behavior.
A.foo(); // implies B.foo()
- In most cases, subclass is also a subtype.
- Inheritance for Extension
- Derived class adds new functionality but does not change inherited behavior.
class Circle { . . . }
class FilledCircle extends Circle {
. . .
protected void fillPattern () { … }
}
Circle C = new FilledCircle(); // by substitution
C.fillPattern();
- Above code will give compilation error even though it will work correctly at runtime.Therefore we use typecasting
(FilledCircle)C.fillPattern(); //OK
- Inheritance for Limitation
- Derived class restricts some of the behavior inherited from the base class.
void fillPattern (class FilledCircle {
FilledCircle() {…}
protected private void fillPattern () { … } }
class NoFilledCircle extends FilledCircle {
NoFilledCircle() {…}
protected ) { … } }
FilledCircle FC;
NoFilledCircle nFC = new NoFilledCircle();
FC = nFC;
nFC.fillPattern(); // compilation error
FC.fillPattern(); // runtime exception
- Java does not provide a good way to facilitate it, use of protected modifier is not a good way.
- In subclasses, which are not subtypes subclassing makes previously permitted operations illegal.
- As it is counter to OOC’s Substitution / Reusability, it is not an encouraging stuff.
- Inheritance for Construction
- A derived class inherits most of the functionality from a base class, changing only the method-names or the arguments.
- e.g. Using List as stack or queue. One is LIFO with functions push() and pop() while other is FIFO with functions add() and delete(). Both use functions having same functionality but different names and arguments.
- Maintains class – subclass relationship.Subclass is not a subtype.Breaks the principle of substitutability.Widely used due to creation of data abstractions.
- Inheritance for Combination : Multiple Inheritance
- Ability of a class to inherit from two or more classes / interfaces.
- New abstraction to be formed as a combination of features from two or more abstractions.
- Implement Multiple Inheritance
- With one class and multiple interfaces,
- Ex. A Tutor is both a student and a teacher.
- Thread : Class vs. Interface
- JVM allows an application to have multiple prioritized threads of execution: A scheduler based on thread ‘State’ which are create,start,run,wait,...
- JVM starts with a (non-daemon) thread; gc runs on a daemon thread. Daemon (background) threads do not prevent program from ending, but stops when the main thread stops.
- Issue is whether to extend Thread class or Implement Runnable interface.
- It is compulsory to provide implementation of run() at least for thread class or only for runnable interface.
package Java.lang.Thread
//implementing Thread by extending Thread class
public class MyThread extends Thread{
public void run(){
System.out.println(“CThread"+Thread.currentThread().getName());
} }
//implementing Thread by implementing Runnable interface
public class MyRunnable implements Runnable{
static int myCount = 0;
public void run(){ ++MyRunnable.myCount;
System.out.println(“IThread" + Thread.currentThread().getName());
}}
Thread mythread = new MyThread(); mythread.setName("Th1");
Thread myrunnable = new Thread(new MyRunnable(),"Th2");
// or any constructor
mythread.start(); //Thread started now but not running
myrunnable.start(); // start depends on scheduler