Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object.
class that is inherited is called a superclass (parent class).
lThe class inherits the propertieis called a subclass.(child class)
l Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass and adds its own, unique elements.
class Vehicle {
String brand = "Ford";
String name;
Vehicle()
{
brand="xyz";
}
public void honk() {
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang";
public static void main(String[] args) {
Car myFastCar = new Car();
myFastCar.honk();
System.out.println(myFastCar.brand + " " + myFastCar.modelName+" "+myFastCar.name);
}
}
Member Access and Inheritance
Although a subclass includes all of the members of its superclass, it cannot
access those members of the superclass that have been declared as private.
// Create a superclass.
class A {
int i; // public by default
private int j; // private to A
void setij(int x, int y) {
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A {
int total;
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
class Access {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
Types of inheritance in java
Java does not support Multiple inheritance or Hybrid as it might create ambiguity
Using Super
Whenever a subclass needs to refer to its immediate super class, it can do so by use of the keyword super.
super has two general forms.
Using super to Call Superclass Constructors
A subclass can call a constructor defined by its super class by use of the following form of super:
super(arg-list);
Here, arg-list specifies any arguments needed by the constructor in the superclass.
class A{
A(int a){ System.out.println(“ BIT);}
}
class D extends A{
D(){
super(a);
System.out.println(“BANGALORE”);
}
}
class TestSuper3{
public static void main(String args[]){
D OB1=new D();
}}
Usage of Java super Keyword
Note: super keyword can only be used in the subclass
Most applicable to situations in which member names of a subclass hide members by the same name in the superclass.
super( ) is used, consider this improved version of the BoxWeight( ) class:
// BoxWeight now uses super to initialize its Box attributes.
class BoxWeight extends Box {
double weight; // weight of box
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call super class constructor
weight = m;
}
}
��������
super is used to refer immediate parent class instance variable�
class A{
String color="white";
}
class D extends A{
String color="black";
void printColor(){
System.out.println(color);//prints color of D class
System.out.println(super.color);//prints color of A class
}
}
class TestSuper1{
public static void main(String args[]){
D d=new D();
d.printColor();
}}
14
// Using super to overcome name hiding.
class A {
int i;
}
// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
15
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
This program displays the following:
i in superclass: 1
i in subclass: 2
Although the instance variable i in B hides the i in A, super allows access to the i defined in the superclass.
As you will see, super can also be used to call methods that are hidden by a subclass.
16
Creating a Multilevel Hierarchy
17
class Shape {
public void display()
{
System.out.println("Inside display");
} }
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
} }
class Cube extends Rectangle {
public void volume() {
System.out.println("Inside volume"); } }
public class Tester {
public static void main(String[] arguments) {
Cube cube1 = new Cube(); cube1.display();
cube1.area();
cube1.volume(); } }
18
A Superclass Variable Can Reference a Subclass Object
A major advantage of inheritance is that once you have created a superclass that defines the attributes common to a set of objects, it can be used to create any number of more specific subclasses. Each subclass can precisely tailor its own classification.
class Animal
{
String name="Animal";
void eat()
{
System.out.println("eating...");}
}
class TestSuper2{
public static void main(String args[]){
Animal d=new Dog();
//d.work();
d.eat();
System.out.println(d.name);
}}
class Dog extends Animal
{
String name="dog";
void eat()
{
System.out.println("eating bread...");
}
void bark()
{System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
When Constructors Are Executed
class A
{
A(int a)
{
System.out.println("a constructor");
}
}
class B extends A
{
B(int a)
{
super(10);
System.out.println("b constructor");
}
}
class multi
{
public static void main(String args[])
{
B b=new B(10);
}
}
Method Overriding
when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within its subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden.
When show( ) is invoked on an object of type B, the version of show( ) defined within B is used. That is, the version of show( ) inside B overrides the version declared in A
If you wish to access the superclass version of an overridden method, you can do so by using super. For example, in this version of B, the superclass version of show( ) is invoked within the subclass’ version.
Why Overridden Methods?
overridden methods allow Java to support run-time polymorphism.
Polymorphism is essential to object-oriented programming for one reason:
Dynamic Method Dispatch
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time.
30
31
// Dynamic Method Dispatch
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
32
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
Note: r being the object reference of A can hold only the subclass object or the object of the same class
33
Using Abstract Classes
sometimes we want to create a superclass that determines the nature of the methods that the subclasses must implement then we use abstract classes.
One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method.
Example:
Rules made
Using Abstract Classes
because they have no implementation specified in the superclass.
Thus, a subclass must override them—it cannot simply use the version defined in the superclass.
To declare an abstract method, use this general form:
abstract type name(parameter-list); abstract void add(int a,intb);
As you can see, no method body is present
35
36
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
37
class AbstractDemo {
public static void main(String args[]) {
B b= new B();
b.callme();
b.callmetoo();
}
}
38
Using final with Inheritance�
1)Using final to Prevent Overriding
39
The following fragment illustrates final:
final class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
40
2)Using final to Prevent Inheritance
Here is an example of a final class:
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
As the comments imply, it is illegal for B to inherit A since A is declared as final
41