Module 3 Complete
Module 3 Complete
3.19 Inheritance
Java, Inheritance is an important pillar of OOP(Object-Oriented Programming).
It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class.
In Java, Inheritance means creating new classes based on existing ones.
A class that inherits from another
class can reuse the methods and fields of that class.
In addition, you can add new fields and methods to your current class as well.
Why Do We Need Java Inheritance?
Code Reusability: The code written in the Superclass is common to all subclasses.
Child classes can directly use the parent class code.
Method Overriding: Method Overriding is achievable only through Inheritance.
It is one of the ways by which Java achieves Run Time Polymorphism.
Abstraction: The concept of abstract where we do not have to provide all details is achieved through inheritance.
Abstraction only shows the functionality to the user.
Important Terminologies Used in Java Inheritance
Class: Class is a set of objects which shares common characteristics/ behavior and common properties/ attributes.
Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created.
Super Class/Parent Class: The class whose features are inherited is known as a superclass(or a base class or a parent class).
Sub Class/Child Class: The class that inherits the other class is known as a subclass(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.
How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java.
Using the extends keyword indicates you are derived from an existing class. In other words, “extends” refers to increased functionality.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
Inheritance is one of the building blocks of object oriented programming languages. It allows creation of
classes with hierarchical relationship among them. Using inheritance, one 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. In the terminology of Java, a class that is inherited
is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a
specialized version of a superclass. It inherits all of the instance variables and methods defined by the
superclass and add its own, unique elements. Through inheritance, one can achieve re-usability of the
code.
In Java, inheritance is achieved using the keyword extends. The syntax is given below:
class A
{
int i, j;
void showij()
{
[Link]("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
void showk()
{
[Link]("k: " + k);
}
void sum()
{
[Link]("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
public static void main(String args[])
{
A superOb = new A();
B subOb = new B();
superOb.i = 10;
superOb.j = 20;
[Link]("Contents of superOb: ");
[Link]();
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
[Link]("Contents of subOb: ");
[Link]();
[Link]();
Note that, private members of the super class can not be accessed by the sub class. The subclass
contains all non-private members of the super class and also it contains its own set of members to
achieve specialization.
superclass
subclass
Multilevel Inheritance: If several classes are inherited one after the other in a hierarchical
manner, it is known as multilevel inheritance, as shown below –
class Base
{
void dispB()
{
[Link]("Super class " );
}
}
class Derived extends Base
{
void dispD()
{
[Link]("Sub class ");
}
}
class Demo
{
public static void main(String args[])
{
Base b = new Base();
Derived d=new Derived();
Note that, the type of reference variable decides the members that can be accessed, but not the type
of the actual object. That is, when a reference to a subclass object is assigned to a superclass
reference variable, you will have access only to those parts of the object defined by the superclass.
class Box
{
double w, h, b;
Also, if the data members of super class are private, then we can’t even write such a code in subclass
constructor. If we use super() to call superclass constructor, then it must be the first statement
executed inside a subclass constructor as shown below –
class Box
{
double w, h, b;
Box(double wd, double ht, double br)
{
w=wd; h=ht; b=br;
}
}
class Demo
{
public static void main(String args[])
{
ColourBox b=new ColourBox(2,3,4, 5);
}
}
Here, we are creating the object b of the subclass ColourBox . So, the constructor of this class is
invoked. As the first statement within it is super(wd, ht, br), the constructor of superclass Box is
invoked, and then the rest of the statements in subclass constructor ColourBox are executed.
To access superclass member variable when there is a duplicate variable name in the
subclass: This form of super is most applicable to situations in which member names of a
subclass hide members by the same name in the superclass.
class A
{
int a;
}
class B extends A
{
int a; //duplicate variable a
B(int x, int y)
{
super.a=x; //accessing superclass a
a=y; //accessing own member a
}
void disp()
{
[Link]("super class a: "+ super.a);
[Link]("sub class a: "+ a);
}
}
class SuperDemo
{
public static void main(String args[])
{
B ob=new B(2,3);
[Link]();
}
}
class A
{ int a;
}
class B extends A
{ int b;
}
class C extends B
{ int c;
class MultiLevel
{
public static void main(String args[])
{
C ob=new C(2,3,4);
[Link]();
}
}
class A
{
A()
{
[Link]("A's constructor.");
}
}
class B extends A
{
B()
{
[Link]("B's constructor.");
}
}
class C extends B
{
C()
{
[Link]("C's constructor.");
}
}
class CallingCons
{
public static void main(String args[])
{
C c = new C();
}
}
Output:
A's constructor
B's constructor
C's constructor
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
void show() //suppressed
{
[Link]("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
void show() //Overridden method
{
[Link]("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
[Link]();
}
}
Output:
k: 3
Note that, above program, only subclass method show() got called and hence only k got displayed. That
is, the show() method of super class is suppressed. If we want superclass method also to be called, we
can re-write the show() method in subclass as –
void show()
{
[Link](); // this calls A's show()
[Link]("k: " + k);
}
Method overriding occurs only when the names and the type signatures of the two methods (one in
superclass and the other in subclass) are identical. If two methods (one in superclass and the other in
subclass) have same name, but different signature, then the two methods are simply overloaded.
class A
{
void callme()
{
[Link]("Inside A");
}
}
class B extends A
{
void callme()
{
[Link]("Inside B");
}
}
class C extends A
{
void callme()
{
[Link]("Inside C");
}
}
class Dispatch
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
A r; //Superclass reference
r = a; //holding subclass object
[Link]();
r = b;
[Link]();
r = c;
[Link]();
}
}
A class containing at least one abstract method is called as abstract class. Abstract classes can not be
instantiated, that is one cannot create an object of abstract class. Whereas, a reference can be created
for an abstract class.
abstract class A
{
abstract void callme();
void callmetoo()
{
[Link]("This is a concrete method.");
}
}
class B extends A
{
void callme() //overriding abstract method
{
[Link]("B's implementation of callme.");
}
}
class AbstractDemo
{
public static void main(String args[])
{
B b = new B(); //subclass object
[Link](); //calling abstract method
[Link](); //calling concrete method
}
}
Example: Write an abstract class shape, which has an abstract method area(). Derive three classes
Triangle, Rectangle and Circle from the shape class and to override area(). Implement run-time
polymorphism by creating array of references to supeclass. Compute area of different shapes and display
the same.
Solution:
class AbstractDemo
{
public static void main(String args[])
{
Shape r[]={new Triangle(3,4), new Rectangle(5,6),new Circle(2)};
for(int i=0;i<3;i++)
[Link](r[i].area());
}
}
Output:
Area of Triangle is:6.0
Area of Rectangle is:30.0
Area of Circle is:12.5664
Note that, here we have created array r, which is reference to Shape class. But, every element in r is
holding objects of different subclasses. That is, r[0] holds Triangle class object, r[1] holds Rectangle class
object and so on. With the help of array initialization, we are achieving this, and also, we are calling
respective constructors. Later, we use a for-loop to invoke the method area() defined in each of these
classes.
To create the equivalent of a named constant: A variable can be declared as final. Doing so prevents
its contents from being modified. This means that you must initialize a final variable when it is declared.
For example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
It is a common coding convention to choose all uppercase identifiers for final variables. Variables
declared as final do not occupy memory on a per-instance basis. Thus, a final variable is essentially a
constant.
To prevent Inheritance: As we have discussed earlier, the subclass is treated as a specialized class
and superclass is most generalized class. During multi-level inheritance, the bottom most class will be
with all the features of real-time and hence it should not be inherited further. In such situations, we can
prevent a particular class from inheriting further, using the keyword final. For example –
final class A
{
// ...
}
class B extends A // ERROR! Can't subclass A
{
// ...
}
Note:
Declaring a class as final implicitly declares all of its methods as final, too.
It is illegal to declare a class as both abstract and final since an abstract class is incomplete by
itself and relies upon its subclasses to provide complete implementations
Method Purpose
Object clone( ) Creates a new object that is the same as the object being cloned.
void notifyAll( ) Resumes execution of all threads waiting on the invoking object.
The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may override
the others. The equals( ) method compares the contents of two objects. It returns true if the objects
are equivalent, and false otherwise. The precise definition of equality can vary, depending on the
type of objects being compared. The toString( ) method returns a string that contains a description of
the object on which it is called. Also, this method is automatically called when an object is output
using println( ). Many classes override this method.
Question Bank:
1. Define class. Give syntax and example.
2. Briefly explain static members of the class with suitable examples.
3. Discuss method overloading. Write a program to overload a method area() to compute area of a
triangle and a circle.
4. Define a constructor. What are the salient features of Constructor? Write a Java program to show
these features.
5. How do you overload a constructor? Explain with a program.
6. Define recursion. Write a recursive program to find nth Fibonacci number.
7. Write a program to implement stack operations.
8. What are different parameter passing techniques in Java? Discuss the salient features of the
same.
9. What are various access specifiers in Java? List out the behaviour of each of them.
10. Create a Java class called Student with the following details as variables (USN, Name, Branch,
Phone Number). Write a Java program to create n student objects and print USN, Name, Branch,
and Phone number with suitable heading.
11. What is inheritance? Discuss different types of inheritance with suitable example.
12. Discuss the behavior of constructors when there is a multilevel inheritance. Give appropriate code
to illustrate the process.
13. Mention and explain the uses of super keyword in Java.
14. How do you pass arguments to superclass constructor through the subclass constructor? Explain
with a code snippet.
15. Discuss usage of final keyword in Java. Give suitable examples.
16. What do you mean by method overriding? Discuss with a programming example.
17. Explain abstract class and abstract method with suitable code snippet.
18. Write a note on:
a. Use of this keyword
b. Garbage Collection in Java
c. Finalize() method
d. Object Class
e. Dynamic Method Dispatch
19. Create an abstract class called Employee. Include the members: Name, EmpID and an abstract
method cal_sal(). Create two inherited classes SoftwareEng (with the members basic and DA)
and HardwareEng (with members basic and TA). Implement runtime polymorphism (dynamic
method dispatch) to display salary of different employees by creating array of references to
superclass.
20. Differentiate method overloading and method overriding.
Interface is an abstract type that can contain only the declarations of methods and constants. Interfaces
are syntactically similar to classes, but they do not contain instance variables, and their methods are
declared without any body. Any number of classes can implement an interface. One class may
implement many interfaces. By providing the interface keyword, Java allows you to fully utilize the “one
interface, multiple methods” aspect of polymorphism. Interfaces are alternative means for multiple
inheritance in Java.
interface ICallback
{
void callback(int param);
}
class TestIface
{
public static void main(String args[])
{
ICallback c = new Client();
[Link](42);
// [Link]() //error!!
}
}
Here, the interface ICallback contains declaration of one method callback(). The class Client
implementing this interface is defining the method declared in interface. Note that, the method callback()
is public by default inside the interface. But, the keyword public must be used while defining it inside the
class. Also, the class has its own method test(). In the main() method, we are creating a reference of
interface pointing to object of Client class. Through this reference, we can call interface method, but not
method of the class.
The true polymorphic nature of interfaces can be found from the following example –
interface ICallback
{
void callback(int param);
}
class TestIface
{
public static void main(String args[])
{
ICallback x[]={new Client(), new Client2()};
for(int i=0;i<2;i++)
x[i].callback(5);
}
}
Output:
callback called with 5
Another version of ICallBack
p squared 25
In this program, we have created array of references to interface, but they are initialized to class objects.
Using the array index, we call respective implementation of callback() method.
Note: Interfaces may look similar to abstract classes. But, there are lot of differences between them as
shown in the following table:
Abstract Class Interface
Can have instance methods that implements Are implicitly abstract and cannot have
a default behavior. implementations.
Can have the members with private, Members of a Java interface are public by
protected, etc.. default.
interface SharedConst
{
int FAIL=0; //these are final by default
int PASS=1;
}
Result(double m)
{
mr=m;
}
int res()
{
if(mr<40)
return FAIL;
else return PASS;
}
}
class Exam extends Result implements SharedConst
{
Exam(double m)
{
super(m);
}
switch([Link]())
{
case FAIL:
[Link]("Fail");
break;
case PASS:
[Link]("Pass");
break;
}
}
}
interface A
{
void meth1();
void meth2();
}
interface B extends A
{
void meth3();
}
class IFExtend
{
public static void main(String arg[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Answer the following
1. What is interface in JAVA? Explain with example
2. Explain default interface method with suitable example
3. How static methods can be used in interface? Explain with suitable example
4. What is Private interface methods? Explain
interface NewInterface {
// static method
static void hello()
{
[Link]("Hello, New Static Method Here");
}
// Implementation Class
public class InterfaceDemo implements NewInterface {
@Override
public void overrideMethod(String str)
{
[Link](str);
}
}
Output:
Hello, New Static Method Here
Hello, Override Method here