Java Unit2
Java Unit2
UNIT-2
INHERITANCE
Inheritance: Inheritance is the process by which objects of one class acquire the properties of
objects of another class. Inheritance supports the concept of hierarchical classification. A deeply
inherited subclass inherits all of the attributes from each of its ancestors in the class hierarchy.
Most people naturally view the world as made up of objects that are related to each
other in a hierarchical way.
Inheritance: A new class (subclass, child class) is derived from the existing class(base class,
parent class).
1. Reusability
2. Abstraction
Syntax:
{ Declaration of variables;
Declaration of methods;
}
JAVA PROGRAMMING
Super class: In Java a class that is inherited from is called a super class.
Sub class: The class that does the inheriting is called as subclass.
extends: To inherit a class, you simply incorporate the definition of one class into another by
using the extends keyword.
The “extends” keyword indicates that the properties of the super class name are extended to the
subclass name. The sub class now contain its own variables and methods as well those of the
super class. This kind of situation occurs when we want to add some more properties to an
existing class without actually modifying the super class members.
// Create a superclass.
class A
{
int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A
{
int k;
void showk()
{
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
public static void main(String args[])
{
JAVA PROGRAMMING
Hierarchical abstractions:
Hierarchical abstractions of complex systems can also be applied to computer programs. The
data from a traditional process-oriented program can be transformed by abstraction into its
component objects.
A sequence of process steps can become a collection of messages between these objects.
Thus, each of these objects describes its own unique behavior.
You can treat these objects as concrete entities that respond to messages telling them to do
something. This is the essence of object-oriented programming.
JAVA PROGRAMMING
Types of Inheritance are use to show the Hierarchical abstractions. They are:
Single Inheritance
Multiple Inheritance
Hierarchical Inheritance
Multilevel Inheritance
Hybrid Inheritance
Single Inheritance: Simple Inheritance is also called as single Inheritance. Here One subclass is
deriving from one super class.
SUPER CLASS A
EXTENDS
SUB CLASS B
Example:
//single inheritance
//consists of only one super class and one sub class
class superclass
{
int a=10,b=20;
void sup_method()
{
System.out.println("This is super class method");
}
}
class subclass extends superclass
{
JAVA PROGRAMMING
int c=30;
void display()
{
System.out.println("The given values are:"+a+","+b+ " & " +c);
}
}
class single_inheritance
{
public static void main(String ar[])
{
subclass obj=new subclass();
obj.sup_method();
obj.display();
}
}
Output:
F:\JAVA Programs for ECE>javac single_inheritance.java
F:\JAVA Programs for ECE>java single_inheritance
This is super class method
The given values are:10,20 & 30
Multiple Inheritance: Deriving one subclass from more than one super classes is called
multiple inheritance.
INTERFACE1 INTERFACE2
A B
(Animal) (Bird)
IMPLEMENTS
SUBCLASS(InterfaceDemo2)
We know that in multiple inheritance, sub class is derived from multiple super classes. If two
super classes have same names for their members then which member is inherited into the sub
class is the main confusion in multiple inheritance. This is the reason; Java does not support the
JAVA PROGRAMMING
Interface: An interface is a class containing a group of constants and method declarations that
does not provide implementation. In essence, an interface allows you to specify what a class
must do, but not how to do.
Interface syntax:
All the methods in an interface must be abstract and public. If we not mention these
keywords then JVM will treats all methods as public and abstract implicitly.
}
public class InterfaceDemo2 implements Animal,Bird
{
public void moves()
{
System.out.println("animal move on land");
}
public void fly()
{
System.out.println("birds fly in air");
}
public static void main(String args[])
{
InterfaceDemo2 id=new InterfaceDemo2();
id.moves();
id.fly();
}
}
Output:
D:\aruns>javac InterfaceDemo2.java
D:\aruns>java InterfaceDemo2
animal move on land
birds fly in air
Hierarchical Inheritance: Only one base class but many derived classes.
SUPERCLASS
Figure
EXTENDS
Rectangle Triangle SUBCLASS
Example:
//hierarchical inheritance
class parent
{
int p1=1000;
int p2=2000;
}
//subclass1
class child1 extends parent
{
int p3=3000;
JAVA PROGRAMMING
void display()
{
System.out.println("Child1 Properties");
System.out.println(p1+" "+p2+" "+p3);
System.out.println("----------------------");
}
}
class child2 extends parent
{
int p4=6000;
void show()
{
System.out.println("Child2 Properties");
System.out.println(p1+" "+p2+" "+p4);
}
}
class hierarchical_inheritance
{
public static void main(String ar[])
{
child1 obj=new child1();
obj.display();
child2 obj1=new child2();
obj1.show();
}
}
Output:
F:\JAVA Programs for ECE>javac hierarchical_inheritance.java
F:\JAVA Programs for ECE>java hierarchical_inheritance
Child1 Properties
1000 2000 3000
----------------------
Child2 Properties
1000 2000 6000
JAVA PROGRAMMING
Multilevel Inheritance: In multilevel inheritance the class is derived from the derived class.
SUPER-CLASS
A
extends
B
SUB-CLASS
C extends
SUB-SUBCLASS
Example:
//multi-level inheritance
class X
{
int rollno=401;
}
class Y extends X
{
String name="ABC";
}
class Z extends Y
{
String college="NEC";
void display()
{
System.out.println("Roll Number= "+rollno+ " Name= "+ name+ "
College= "+college);
}
}
class multilevel_inheritance
{
public static void main(String ar[])
{
Z obj=new Z();
obj.display();
}
}
JAVA PROGRAMMING
Output:
F:\JAVA Programs for ECE>javac multilevel_inheritance.java
F:\JAVA Programs for ECE>java multilevel_inheritance
Roll Number= 401 Name= ABC College= NEC
A
HIERARCHICAL
B C
MULTIPLE
D
“super” Keyword:
Whenever a subclass needs to refer to its immediate super class, it can do so by the use of the
keyword super.
2. super.member: To access a member of the super class that has been hidden by a member of a
subclass. Member may be variable or method.
Use: Overridden methods allow Java to support Run-time polymorphism. This leads to
Robustness by Reusability.
super can be used to refer super class constructor as: super (values)
1. Example program for super can be used to refer super class constructor as: super
(values)
class Figure
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1=a;
dim2=b;
}
}
class Rectangle extends Figure
{
Rectangle(double a,double b)
{ calling super class constructor
super(a,b);
}
double area()
{
System.out.println("Inside area for rectangle");
return dim1*dim2;
}
}
class Triangle extends Figure
{
Triangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("Inside area for triangle");
return dim1*dim2/2;
}
}
class FindAreas
{
public static void main(String args[])
{
Rectangle r=new Rectangle(9,5);
Triangle t=new Triangle(10,8);
System.out.println("area is"+r.area());
JAVA PROGRAMMING
System.out.println("area is"+t.area());
}
}
Output:
D:\aruns>javac FindAreas.java
D:\aruns>java FindAreas
Inside area for rectangle
area is45.0
Inside area for triangle
area is40.0
2.Accessing the member of a super class:
The second form of super acts somewhat like this, except that it always refers to the
superclass of the subclass in which it is used.
Here, member can be either a method or an instance variable. This second form of super is most
applicable to situations in which member names of a subclass hide members by the same name
in the superclass. Consider this simple class hierarchy:
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);
}
}
class UseSuper
{
JAVA PROGRAMMING
import java.io.*;
class A
{
void display()
{
System.out.println("hi");
}
}
class B extends A
{
void display()
{ calling super class method
super.display();
System.out.println("hello");
}
static public void main(String args[])
{
B b=new B();
b.display();
}
}
Output:
D:\aruns>javac B.java
D:\aruns>java B
hi
hello
Abstract classes:
A method with method body is called concrete method. In general any class will have all
concrete methods.
It is possible to implement the abstract methods differently in the subclasses of an abstract
class.
These different implementations will help the programmer to perform different tasks
depending on the need of the sub classes. Moreover, the common members of the abstract class
are also shared by the sub classes.
The abstract methods and abstract class should be declared using the keyword abstract.
An abstract class contains instance variables & concrete methods in addition to abstract
methods.
All the abstract methods of the abstract class should be implemented in its sub classes.
If any method is not implemented, then that sub class should be declared as ‘abstract’.
JAVA PROGRAMMING
Abstract class reference can be used to refer to the objects of its sub classes.
Abstract class references cannot refer to the individual methods of sub classes.
“final” Keyword
”final” is a keyword in Java which generically means, cannot be changed once created. Final
behaves very differently when variables, methods and classes. Any final keyword when declared
with variables, methods and classes specifically means:
Classes are usually declared final for either performance or security reasons. Final methods
work like inline code of C++.
Final variables work like const of C-language that can’t be altered in the whole program. That is,
final variables once created can’t be changed and they must be used as it is by all the program
code.
Example program:
import java.io.*;
class FinalVar
{
int x=10;
final int y=20;
System.out.println("x is:"+x);
System.out.println("y is:"+y);
x=30;
y=40;
System.out.println("x is:"+x);
System.out.println("y is:"+y);
}
}
Output:
Cannot assign a value to final variable y
“final” with methods:
Generally, a super class method can be overridden by the subclass if it wants a different
functionality. Or, it can call the same method if it wants the same functionality. If the super class
desires that the subclass should not override its method, it declares the method as final. That is,
methods declared final in the super class cannot be overridden in the subclass(else it is
compilation error). But, the subclass can access with its object as usual.
Example program:
import java.io.*;
class A
JAVA PROGRAMMING
System.out.println("hi");
class B extends A
void display()
super.display();
System.out.println("hello");
B b=new B();
b.display();
Output:
Example program:
import java.io.*;
final class Demo1
{
public void display()
{
System.out.println("hi");
}
}
public class Demo3 extends Demo1
{
public static void main(String args[])
{
Demo1 d=new Demo1();
d.display();
}}
Output:
D:\aruns>javac Demo3.java
Demo3.java:9: cannot inherit from final Demo1
public class Demo3 extends Demo1
^
1 error
Polymorphism:
Polymorphism came from the two Greek words ‘poly’ means many and ‘morphos’ means
forms.
If the same method has ability to take more than one form to perform several tasks
then it is called polymorphism.
It is of two types:
Dynamic polymorphism(Runtime polymorphism)
The polymorphism exhibited at run time is called dynamic polymorphism. In this dynamic
polymorphism a method call is linked with method body at the time of execution by JVM. Java
compiler does not know which method is called at the time of compilation. This is also
known as dynamic binding or run time polymorphism.
o Method Overloading: Writing two or more methods with the same name with different
parameters is called method over loading.. In method overloading JVM understands which
method is called depending upon the difference in the method parameters. The difference may
be due to the following:
// overloading of methods
class Sample
{
void add(int a, int b)
{
System.out.println ("sum of two="+ (a+b));
}
JAVA PROGRAMMING
class Animal
{
void move()
{
System.out.println ("Animals can move");
}
}
class Dog extends Animal
{
void move()
{
System.out.println ("Dogs can walk and run");
}
}
public class OverRide
{
public static void main(String args[])
{
Animal a = new Animal (); // Animal reference and object
Animal b = new Dog (); // Animal reference but Dog object
JAVA PROGRAMMING
Benefits of Inheritance:
Increased reliability
Software reusability
Code sharing
Consistency of interface
Polymorphism
Information hiding
Rapid prototyping
Costs of inheritance:
Program size
Execution speed
Program complexity
Message-passing