Inheritance in Java
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.
Types inheritance
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes, it is also known as simple inheritance. In the below
figure, ‘A’ is a parent class and ‘B’ is a child class. The class ‘B’ inherits all the properties of the
class ‘A’.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived
class also acts as the base class for other classes. In the below image, class A serves as a base class
for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class
cannot directly access the grandparent’s members.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass.
In the below image, class A serves as a base class for the derived classes B, C, and D.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
4. Multiple Inheritance (Through Interfaces)
In Multiple inheritances, one class can have more than one superclass and inherit features from all
parent classes. Please note that Java does not support multiple inheritances with classes. In Java,
we can achieve multiple inheritances only through Interfaces. In the image below, Class C is
derived from interfaces A and B.
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
Rules for Java Method Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance)
//Java Program to demonstrate why we need method overriding
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs"
means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can
perform polymorphism in java by method overloading and method overriding.If you overload a static method
in Java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.
Runtime Polymorphism in Java
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden
method is resolved at runtime rather than compile-time.In this process, an overridden method is called through
the reference variable of a superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.Let's first understand the upcasting before Runtime Polymorphism.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For
example:
class A{}
class B extends A{}
A a=new B();//upcasting
For upcasting, we can use the reference variable of class type or an interface type. For Example:
interface I{}
class A{}
class B extends A implements I{}
Here, the relationship of B class would be:
B IS-A A
B IS-A I
B IS-A Object
Example of Java Runtime Polymorphism
In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and
overrides its run() method. We are calling the run method by the reference variable of Parent class.
Since it refers to the subclass object and subclass method overrides the Parent class method, the
subclass method is invoked at runtime.Since method invocation is determined by the JVM not
compiler, it is known as runtime polymorphism.
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");
}
public static void main(String args[]){
Bike b = new Splendor();//upcasting
b.run();
}
}
running safely with 60km.
Static Binding and Dynamic Binding
Connecting a method call to the method body is known as binding.
There are two types of binding
1. Static Binding (also known as Early Binding).
2 .Dynamic Binding (also known as Late Binding).
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");
}
public static void main(String args[]){
Animal a=new Dog();
a.eat();
}
}
Test it Now
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance of
Dog is also an instance of Animal.So compiler doesn't know its type, only its base type.
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the
code stable by detecting the bugs at compile time.Before generics, we can store any type of objects
in the collection, i.e., non-generic. Now generics force the java programmer to store a specific type of
objects.
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:
1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store other
objects.
Without Generics, we can store any type of objects.
1. List list = new ArrayList();
2. list.add(10);
3. list.add("10");
4. With Generics, it is required to specify the type of object we need to store.
5. List<Integer> list = new ArrayList<Integer>();
6. list.add(10);
7. list.add("10");// compile-time error
2) Type casting is not required: There is no need to typecast the object.
Before Generics, we need to type cast.
1. List list = new ArrayList();
2. list.add("hello");
3. String s = (String) list.get(0);//typecasting
4. After Generics, we don't need to typecast the object.
5. List<String> list = new ArrayList<String>();
6. list.add("hello");
7. String s = list.get(0);
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The
good programming strategy says it is far better to handle the problem at compile time than runtime.
1. List<String> list = new ArrayList<String>();
2. list.add("hello");
3. list.add(32);//Compile Time Error
Java instanceof operator
The java instanceof operator is used to test whether the object is an instance of the specified type
(class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the instance
with type. It returns either true or false. If we apply the instanceof operator with any variable that has
null value, it returns false.
Simple example of java instanceof
Let's see the simple example of instance operator where it tests the current class.
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Abstract Method
A method declared using the abstract keyword within an abstract class and does not have a definition
(implementation) is called an abstract method.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o An abstract method do not have a body (implementation), they just have a method signature
(declaration).
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.
Example of Abstract class that has an abstract method
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){ Bike obj = new Honda4();
obj.run();
}
}
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.The interface in
Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not
method body. It is used to achieve abstraction and multiple inheritance in Java.In other words, you can say
that interfaces can have abstract methods and variables. It cannot have a method body.
Java Interface also represents the IS-A relationship.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final
by default. A class that implements an interface must implement all the methods declared in the
interface.
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Simple example of java package
The package keyword is used to create a package in java.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }