Unit 4
Unit 4
2. Using inheritance, you can create a general class that defines traits common
to a set of related items. This class can then be inherited by other, more
specific classes, each adding those things that are unique to it.
Important terminology:
Super Class: The class whose features are inherited is known as super
class(or a base class or a paren class).
Sub Class: The class that inherits the other class is known as sub
class(or a derived class, extended class, or child class). The subclass
can add its own fields and methods in addition to the superclass fields
and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when
we want to create a new class and there is already a class that includes
some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of
the existing class.
To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword. To see how, let’s begin with a short
example. The following program creates a superclass called A and a subclass
called B. Notice how the keyword extends is used to create a subclass of A.
Inheritance Example
Let’s consider a superclass Vehicle. Different vehicles have different features
and properties however there few of them are common to all. Speed, color, fuel
used, size are few which are common to all. Hence we can create a class
‘Vehicle’ with states and actions that are common to all vehicles. The subclass
of this superclass can be any type of vehicle. Example: Class Car A has all the
features of a vehicle. But it has its own attributes which makes it different
from other subclasses. By using inheritance we need not rewrite the code that
we’ve already used with the Vehicle. The subclass can also be extended. We can
make a class ‘Sports Car’ which extends ‘Car’. It inherits the features of both
The output is
Note:
The derived class inherits all the members and methods that are declared as
public or protected. If declared as private it can not be inherited by the
derived classes. The private members can be accessed only in its own class. The
1) Single Inheritance
Single inheritance is damn easy to understand. When a class extends another one
class only then we call it a single inheritance. The below flow diagram shows
that class B extends only one class which is A. Here A is a parent class of B
and B would be a child class of A.
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
2) Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending (Or
inherits) more than one base class. The inheritance we learnt earlier had the
concept of one base class or parent. The problem with “multiple inheritance” is
that the derived class will have to manage the dependency on two base classes.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not support
Multiple inheritance. Multiple Inheritance is supported in C++.
3) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can
inherit from a derived class, thereby making this derived class the base class
for the new class. As you can see in below flow diagram C is subclass or child
class of B and B is a child class of A.
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
4) Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below
example class B,C and D inherits the same class A. A is parent class (or base
class) of B,C & D.
//Example
Class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
Class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
Class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
Class MyClass
{
public void methodB()
The above would run perfectly fine with no errors and the output would be –
method of Class A
method of Class A
method of Class A
1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
Output:
black
white
In the above example, Animal and Dog both classes have a common property color.
If we print color property, it will print the color of current class by default.
To access the parent property, we need to use super keyword.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call
eat() method from Dog class, it will call the eat() method of Dog class by
default because priority is given to local.
1. class Animal{
2. Animal(){System.out.println("animal is created");}
Output:
animal is created
dog is created
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. System.out.println("dog is created");
7. }
8. }
9. class TestSuper4{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. }}
animal is created
dog is created
1. class Person{
2. int id;
3. String name;
4. Person(int id,String name){
5. this.id=id;
6. this.name=name;
7. }
8. }
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constructor
13. this.salary=salary;
14. }
15. void display(){System.out.println(id+" "+name+" "+salary);}
16. }
17. class TestSuper5{
18. public static void main(String[] args){
19. Emp e1=new Emp(1,"ankit",45000f);
20. e1.display();
21. }}
Output:
1 ankit 45000
method overriding:
In a class hierarchy, 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 a 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.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
k: 3
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
If you substitute this version of A into the previous program, you will see the
following output:
i and j: 1 2
k: 3
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show("This is k: "); // this calls show() in B
subOb.show(); // this calls show() in A
}
}
This is k: 3
i and j: 1 2
An object of the class triangle, will gives a triangle , again a common everyday
shape
If you observe the Shape class serves in our goal of achieving inheritance and
polymorphism . But it was not built to be instantiated.Such classes can be
labeled Abstract.An abstract class can not be instantiated.
Ex.
It is possible that you DO NOT label Shape class as Abstract and then
instantiate it. But such object will have no use in your code and will open a
room for potential errors. Hence this is not desirable.
A factory method is the method that returns the instance of the class. We will
learn about the factory method later.
In this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.
File: TestAbstraction1.java
drawing circle
Interface in JAVA
The java compiler adds public and abstract keywords before the interface method.
More, it adds public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and
methods are public and abstract.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Output:
Hello
File: TestInterface1.java
Output:
drawing circle
File: TestInterface2.java
1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}
Output:
ROI: 9.15
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }
Output:Hello
Welcome
Output:
Hello
As you can see in the above example, Printable and Showable interface have same
methods but its implementation is provided by class TestTnterface1, so there is
no ambiguity.
Interface inheritance
A class implements interface but one interface extends another interface .
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. TestInterface4 obj = new TestInterface4();
13. obj.print();
14. obj.show();
15. }
16. }
Output:
Hello
Welcome
interface Foo{
void display();
}
void display(){
System.out.println(“Hello World”);
}
1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple1);//true
5. }
6. }
Output:true
An object of subclass type is also a type of parent class. For example, if Dog
extends Animal then object of Dog can be referred by either Dog or Animal class.
Output:true
1. class Dog2{
2. public static void main(String args[]){
3. Dog2 d=null;
4. System.out.println(d instanceof Dog2);//false
5. }
6. }
Output:false
1. class Animal { }
2.
3. class Dog3 extends Animal {
4. static void method(Animal a) {
5. if(a instanceof Dog3){
6. Dog3 d=(Dog3)a;//downcasting
7. System.out.println("ok downcasting performed");
8. }
1. class Animal { }
2. class Dog4 extends Animal {
3. static void method(Animal a) {
4. Dog4 d=(Dog4)a;//downcasting
5. System.out.println("ok downcasting performed");
6. }
7. public static void main (String [] args) {
8. Animal a=new Dog4();
9. Dog4.method(a);
10. }
11. }
1. interface Printable{}
2. class A implements Printable{
3. public void a(){System.out.println("a method");}
4. }
5. class B implements Printable{
6. public void b(){System.out.println("b method");}
7. }
8.
Output: b method
class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type B
B b = new B();
// object of type C
C c = new C();
Output:
Explanation :
The above program creates one superclass called A and it’s two subclasses B and
C. These subclasses overrides m1( ) method.
// class A
class A
{
int x = 10;
}
// class B
class B extends A
{
int x = 20;
}
// Driver class
public class Test
10
Explanation : In above program, both the class A(super class) and B(sub class)
have a common variable ‘x’. Now we make object of class B, referred by ‘a’ which
is of type of class A. Since variables are not overridden, so the statement
“a.x” will always refer to data member of super class.
But there are many differences between abstract class and interface that are
given below.
References:
3. http://www.javacjava.com/tutorials.aspx
4. https://www.javatpoint.com/java-tutorial
5. https://way2java.com/java-lang/
6. https://www.tutorialspoint.com/java/
7. www.studytonight.com/java/
8. https://beginnersbook.com/2013/05/
9. www1.fs.cvut.cz/cz/u12110/prt/java/
11. https://www.guru99.com/
12. www.c4learn.com/java/
13. www.geeksforgeeks.org/
14. www.sitesbay.com/java/
15.https://www.go4expert.com/articles/initialization-block-java-t1254/