BITS Pilani
Hyderabad Campus
BITS Pilani
Hyderabad Campus
Todays Agenda
Objective: derive a new class from existing class Recognize the path of inheritance of classes in JDK Inherence model is the "is-a-relationship", not a "hasrelationship" All of the classes you use or define are implicitly inherited from the top class, Object
INHERITANCE BASICS
1. Reusability is achieved by INHERITANCE
2. Java classes Can be Reused by extending a class. Extending an existing class is nothing but reusing properties of the existing classes.
3. The class whose properties are extended is known as
known as sub
Inheritance
Creating a subclass
Creating a subclass extends properties and methods from the superclass. You can also: Add new properties Add new methods Override the methods of the superclass
<<class>>
A super class
B sub class class B implements A { .. } A interface B sub class
B A
<<class>>
<<interface>>
<<class>>
MultiLevel Inheritance A B A
B
C
CS/IS F213 First Semester 2012-13
C
BITS Pilani, Hyderabad Campus
Forms of Inheritance
Multiple Inheritance can be implemented by implementing multiple interfaces not by extending multiple classes Example :
A class Z extends A implements C , D C D
{ }
OK
class Z extends A ,B {
OR
}
WRONG
}
CS/IS F213 First Semester 2012-13
WRONG
BITS Pilani, Hyderabad Campus
Defining a Subclass
Syntax :
method declarations;
}
Extends keyword signifies that properties of the super class are extended to sub class
Sub class will not inherit private members of super class
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
Inheritance Basics
1. Whenever a sub class object is created ,super class constructor is called first. 2. If super class does not have any constructor of its own OR has an unparametrized constructor then it is automatically called by Java Run Time by using call super() 3. If a super class has a parameterized constructor then it is the responsibility of the sub class constructor to call the super class constructor by call super(<parameters required by super class>) 4. Call to super class constructor must be the first statement in sub class constructor
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
Inheritance Basics
When super class has a Unparametrized constructor
class A { A() { System.out.println("This is constructor of class A"); } } // End of class A class B extends A { B() { super(); System.out.println("This is constructor of class B"); } } // End of class B
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
class inhtest { public static void main(String args[]) { B b1 = new B(); } } OUTPUT This is constructor of class A This is constructor of class B
class A { A() { System.out.println("This is class A"); } } class B extends A { B() { System.out.println("This is class B"); } } class inherit1 { public static void main(String args[]) { B b1 = new B(); } }
CS/IS F213 First Semester 2012-13
class A { private A() { System.out.println("This is class A"); } } class B extends A /* { E:\Java>javac xyz1.java B() xyz1.java:12: A() has private access in { A System.out.println("This is class B"); { } ^ } 1 error class inherit2 */ { public static void main(String args[]) { B b1 = new B(); } } CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
class A { private A() { System.out.println("This is class A"); } A() { System.out.println("This is class A"); } /* } E:\Java>javac xyz2.java class B extends A { xyz2.java:7: A() is already defined in A B() A() { ^ System.out.println("This is class B"); xyz2.java:16: A() has private access in A } { } ^ class inherit2 2 errors { */ public static void main(String args[]) { B b1 = new B(); }} CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
Note:
Private members are not accessible outside the class. If a constructor is made private, then the object also needs to be created within the class. Private constructor cannot be accessed from an inherited class.
D:\java\bin>javac inhtest.java inhtest.java:15: cannot find symbol symbol : constructor A() location: class A { ^ 1 errors
BITS Pilani, Hyderabad Campus
class A { private int a; A( int a) { this.a =a; System.out.println("This is constructor of class A"); }} class B extends A { B b1 = new B(8,10,8.6); private int b; private double c; B(int a,int b,double c) { OUTPUT super(a); This is constructor of class A this.b=b; This is constructor of class B this.c=c; System.out.println("This is constructor of class B"); }}
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
class A { private int a; protected String name; A(int a, String n) { this.a = a; this.name = n; } void print() { System.out.println("a="+a); } }
class B extends A { int b; double c; B(int a,String n,int b,double c) { super(a,n); this.b=b; this.c =c; } void show() { //System.out.println("a="+a); print(); System.out.println("name="+name); System.out.println("b="+b); System.out.println("c="+c); } }
class xyz3 { public static void main(String args[]) { B b1 = new B(10,"OOP",8,10.56); b1.show(); } } E:\Java>java xyz3 a=10 name=OOP b=8 c=10.56
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
class A { private int a; A( int a) { this.a =a; System.out.println("This is constructor of class A"); } void print() { System.out.println("a="+a); } void display() { System.out.println("hello This is Display in A"); } } // End of class A
class B extends A { private int b; private double c; B(int a,int b,double c) { super(a); this.b=b; this.c=c; System.out.println("This is constructor of class B"); } void show() { print(); System.out.println("b="+b); System.out.println("c="+c); } } // End of class B
class inhtest1 { public static void main(String args[]) { B b1 = new B(10,8,4.5); b1.show(); } } /* OutPUt D:\java\bin>java inhtest1 This is constructor of class A This is constructor of class B a=10 b=8 c=4.5 */
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
Super class
Super ob
Sub class
Sub ob
RefDemo.java
Multilevel Inheritance
You can build hierarchies that contain as layer of inheritance as you want. DemoMultiLevel.java
Methods overriding
1. Sub class can override the methods defined by the super class. 2. Overridden Methods in the sub classes should have same name, same signature , same return type and may have either the same or higher scope than super class method. 3. Java implements Run Time Polymorphism/ Dynamic Method Dispatch by Method Overriding. [Late Binding] 4. Call to Overridden Methods is Resolved at Run Time. 5. Call to a overridden method is not decided by the type of reference variable Rather by the type of the object where reference variable is pointing. 6. While Overriding a Method, the sub class should assign either same or higher access level than super class method.
class A { void show() { System.out.println("Hello This is show() in A"); }// End of show() Method } // End of class A B class overrides show() class B extends A { method from super class A void show() { System.out.println("Hello This is show() in B"); }// End of show() Method } // End of class B class override { public static void main(String args[]) { Call to // super class reference variable show() of A // can point to sub class object class A a1 = new A(); a1.show(); Call to a1 = new B(); show() of B a1.show(); } class
CS/IS F213 First Semester 2012-13
Is this Method Overriding class A { NO void show(int a) { System.out.println("Hello This is show() class override1 in A"); { } public static void main(String args[]) } { class B extends A { A a1 = new A(); void show() a1.show(10); { System.out.println("Hello This is show() B b1 = new B(); in B"); b1.show(10); } b1.show(); } } OUTPUT
Hello This is show() in A Hello This is show() in A Hello This is show() in B Method overriding occurs only when the names and the type signatures of the two methods are identical.
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
class override2 { public static void main(String args[]) { A a1 = new A(); a1.show(); a1 = new B(); a1.show(); a1 = new C(); a1.show(); a1 = new D(); a1.show(); } }
class override3 { public static void main(String args[]) { A a1 = new B(); B b1 = (B) a1;
/* A a1 = new B(); C c1 = (C) a1; Exception in thread "main" java.lang.ClassCastException: B at override3.main(override3.java:39) */ } }
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
Examples Overriding
class A { void show() { . } } class B extends A { void show() { . } void show(int x) { } void print() { } } A a1 = new B(); a1.show() ; // Valid // a1.show(10); // Invalid //a1.print(); // Invalid
When a super class variable points to a sub class object, then it can only call overridden methods of the sub class.
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
class A { protected void show() { System.out.println("Hi"); } } class B extends A { void show() { System.out.println("Hi"); } }
D:\Java1>javac AB.java AB.java:10: show() in B cannot override show() in A; attempting to assign weaker access privileges; was protected void show() ^ 1 error
class A { private void show() { System.out.println("Hi"); } } class B extends A { int show() { System.out.println("Hi"); return 10; } }
NO
CODE WILL COMPILE & RUN SUCESSFULLY
sample.java:12: show() in B cannot override show() in A; overridden method is st atic void show() ^ 1 error
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
Nothing
The code will compile and run successfully. Method Hiding B class Hides show() method from super class A
class A { static int show() { System.out.println("SHOW METHOD OF CLASS A"); return 0; }// End of show() Method }// End of class A class B extends A { static int show() { System.out.println("SHOW METHOD OF CLASS B"); return 0; }// End of show() Method }// End of class B
class TestAB { public static void main(String args[]) { A a1 = new B(); System.out.println(a1.show()); B b1 = new B(); b1.show(); } }
class A { private int a; private int b; private int c; A() { a=b=c=10; } A(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public int getA() { return this.a;} public int getB() { return this.b;} public int getC() { return this.c;} public void show() { System.out.println("a="+a); System.out.println("b="+b); System.out.println("c="+c); }// End of show() Method }// End of class A
class B extends A { private int d; B() { super(); d=10; } B(int a, int b, int c,int d) { super(a,b,c); this.d = d; } public int getD() { return this.d;} public void show() { System.out.println("a="+super.getA()); System.out.println("b="+super.getB()); System.out.println("c="+super.getC()); System.out.println("d="+this.d); }// End of show() Method }// End of class B
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
class Test { public static void main(String args[]) { A a1 = new B(); System.out.println(a1.getA()); System.out.println(a1.getD()); a1.show(); }// End of main() Method }// End of class Test
Test.java:56: cannot find symbol symbol : method getD() location: class A System.out.println(a1.getD());
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
Restricting Inheritance
Parent
Inherited capability
Child
Final Members: A way for Preventing Overriding of Members in Subclasses All methods and variables can be overridden by default in subclasses. This can be prevented by declaring them as final using the keyword final as a modifier. For example:
final int marks = 100; final void display();
This ensures that functionality defined in this method cannot be altered any. Similarly, the value of a final variable cannot be altered.
Any attempt to inherit these classes will cause an error. If a class is final, all its methods are also final.
Example
class PersonalLoan{ public final String getName(){ return "personal loan"; } } class CheapPersonalLoan extends PersonalLoan{ public final String getName(){ return "cheap personal loan"; //compilation error: overridden method is final } }
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
Abstract Classes
When we define a class to be final, it cannot be extended. In certain situation, we want to properties of classes to be always extended and used. Such classes are called Abstract Classes. An Abstract class is a conceptual class. An Abstract class cannot be instantiated objects cannot be created.
Abstract classes provides a common root for a group of classes, nicely tied together in a package
} When a class contains one or more abstract methods, it should be declared as abstract class. The abstract methods of an abstract class must be defined in its subclass. We cannot declare abstract constructors or abstract static methods.
No. It is illegal because the Shape class is an abstract class, which cannot be instantiated to create its objects.
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
Abstract Classes
public Circle extends Shape { protected double r; protected static final double PI =3.1415926535; public Circle() { r = 1.0; ) public double area() { return PI * r * r; } } public Rectangle extends Shape { protected double w, h; public Rectangle() { w = 0.0; h=0.0; } public double area() { return w * h; } } CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
A subclass of an abstract class can be instantiated if it overrides all abstract methods by implementation them.
A subclass that does not implement all of the superclass abstract methods is itself abstract; and it cannot be instantiated.
Example
Examples
Which declare a compilable abstract class? (Choose all that apply.) A. public abstract class Canine { public Bark speak(); } B. public abstract class Canine { public Bark speak() { } } C. public class Canine { public abstract Bark speak(); } D. public class Canine abstract { public abstract Bark speak(); }
B is correct. abstract classes don't have to have any abstract methods. A is incorrect because abstract methods must be marked as such. C is incorrect because you can't have an abstract method unless the class is abstract. D is incorrect because the keyword abstract must come before the classname.
Example
public abstract class AbstractClass { public AbstractClass() { System.out.println("this is an abstract class constructor!"); } public void aMethod() { System.out.println("This is in the method in the abstract class"); } } No output compiles successfully
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus
public abstract class Entity { private int id; private Color c; public void setID(int id) { this.id = id } public int getID() { return id; } public void setColor(Color c) { this.c = c; } public Color getColor() { return c; } public abstract void paint(Graphics g); } public class Point extends Entity { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public void paint(Graphics g) { g.setColor(getColor()); g.drawLine(x, y, x, y); } } CS/IS F213 First Semester 2012-13
Summary
If you do not want (properties of) your class to be extended or inherited by other classes, define it as a final class.
Java supports this is through the keyword final. This is applied to classes.
You can also apply the final to only methods if you do not want anyone to override them. If you want your class (properties/methods) to be extended by all those who want to use, then define it as an abstract class or define one or more of its methods as abstract methods.
Java supports this is through the keyword abstract. This is applied to methods only. Subclasses should implement abstract methods; otherwise, they cannot be instantiated.