Unit 2 Inheritance
Unit 2 Inheritance
Use of Inheritance
Code Reusability
Method Overriding (so runtime polymorphism can be achieved).
Forms of Inheritance
Single inheritance [only one super class]
Multiple inheritance [several super classes ]
Hierarchical inheritance [ one super classes, many subclasses]
Multilevel inheritance [derived from a derived class].
Hybrid inheritance
Java does not directly implement multiple inheritances but by
using the concept of secondary inheritance path in the form of
interfaces.
The diagrammatical representation of the forms of inheritance is as follows:
Output:
barking...
eating...
MULTILEVEL INHERITANCE
When there is a chain of inheritance, it is known as multilevel inheritance. As you
can see in the example given below, BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a multilevel inheritance.
EXAMPLE:
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();
}}
Output:
weeping...
barking...
eating...
HIERARCHICAL INHERITANCE
When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.
EXAMPLE:
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
}}
Output
meowing...
eating...
Hybrid Inheritance in Java
A hybrid inheritance is a combination of more than one types of inheritance. For
example when class A and B extends class C & another class D extends class A
then this is a hybrid inheritance, because it is a combination of single and
hierarchical inheritance. Let me show you this diagrammatically:
C
↑
|
---------------
↑ ↑
| |
A B
↑
|
D
Example:
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
}
class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){
SUPER KEYWORD:
The super keyword in java is a reference variable that is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is
created implicitly i.e. referred by super reference variable.
Use of Super:
Super is used to refer immediate parent class instance variable
super() is used to invoke immediate parent class constructor
super is used to invoke immediate parent class method
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.
Use of Java Method Overriding
Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
The method must have the same name as in the parent class
The method must have the same parameter as in the parent class.
There must be an IS-A relationship (inheritance).
Understanding the problem without method overriding
Let's understand the problem that we may face in the program if we don't use
method overriding.
EXAMPLE:
//Java Program to demonstrate why we need method overriding
//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
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();
} }
Output:
Vehicle is running
Output
Woof
Dynamic method dispatch
Method overriding is one of the ways in which Java supports Runtime
Polymorphism. Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run time, rather than compile
time.
When an overridden method is called through a superclass reference, Java
determines which version (superclass/subclasses) of that method is to be
executed based upon the type of the object being referred to at the time the
call occurs. Thus, this determination is made at run time.
At run-time, it depends on the type of the object being referred to (not
the type of the reference variable) that determines which version of an
overridden method will be executed
A superclass reference variable can refer to a subclass object. This is
also known as upcasting. Java uses this fact to resolve calls to overridden
methods at run time.
OBJECT CLASS
The Object class is the parent class of all the classes in java by default.
In other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type
you don't know. Notice that parent class reference variable can refer the
child class object, know as upcasting.
PACKAGES
Introduction:
Packages provide a mechanism for grouping a variety of classes and / or
interfaces together.
Grouping is based on functionality
Benefits of Packages:
The classes contained in the packages of other programs can be reused. In
packages, classes can be unique compared with classes in other packages.
A package provides a way to hide classes.
Types of packages:
Pre-defined packages or Java API packages
User-defined packages
Java API packages:
A large number of classes grouped into different packages based on
functionality.
Examples:
java.lang
java.util
java.io
java.awt
java.net
java.applet etc.
Accessing Classes in a Package:
1. Fully Qualified class name: Example:java.awt.Color
2. import packagename.classname; Example: import java.awt.Color;
or
import packagename.*; Example: import java.awt.*;
Import statement must appear at the top of the file, before any class declaration
Creating Your Own Package
1. Declare the package at the beginning of a file using the form package
packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory with same name as package name under the directory
where the main source files are stored.
4. Store the listing as classname.java in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory
Syntax:
package [PackageName];
public class [ClassName]
{
//Body of the class
}
Example:
package firstPackage;
public class FirstClass
{
//Body of the class
}
Example:
//Class in package package p1;
public class ClassA
{
public void displayA( )
{
System.out.println(“Class A”);
}
}
//Importing class from package import p1.*;
class testclass
{
public static void main(String str[])
{
ClassA obA=new ClassA();
obA.displayA();
}}
Creating Packages:
Consider the following declaration: package firstPackage.secondPackage;
This package is stored in subdirectory named firstPackage.secondPackage.
A java package can contain more than one class definitions that can be
declared as public.
Only one of the classes may be declared public and that class name with
.java extension is the source file name.
Default Package:
• If a source file does not begin with the package statement, the classes
contained in the source file reside in the default package
• The java compiler automatically looks in the default package to find classes
Finding Packages:
1. By default, java runtime system uses current directory as starting
point and search all the subdirectories for the package.
2. Specify a directory path using CLASSPATH environmental variable
ACCESS SPECIFIERS:
Access specifiers specifies the type of access levels for the classes,
variables, methods and constructor
Types of access-specifiers:
Default - Visible to the package, the default.
Private - Visible to the class only.
Public - Visible to the world.
Protected -Visible to the package and all subclasses.
Levels of Access Control:
public protected friendly (default) private
INTERFACES
An interface in java is a blueprint of a class. It has static constants and
abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There
can be only abstract methods in the java interface not method body.
It is used to achieve fully abstraction and multiple inheritances in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Use of Interface:
There are mainly three reasons to use interface. They are given below.
It is used to achieve fully abstraction.
By interface, we can support the functionality of multiple inheritances.
It can be used to achieve loose coupling.
interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output: Hello
Example:
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){
System.out.println("Hello");}
public void show(){
System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome