JAVA –Unit2 PESIAMS,Shimoga
Inheritance in Java is a mechanism in which one object acquires
all the properties and behaviors of a parent object. It is an important
part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create
new classes that are built upon existing classes. When you inherit
from an existing class, you can reuse methods and fields of the
parent class. Moreover, you can add new methods and fields in your
current class also.
Inheritance represents the IS-A relationship which is also known
as a parent-child relationship.
erms used in Inheritance
o Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when you
create a new class. You can use the same fields and methods already defined
in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
n java programming, multiple and hybrid inheritance is supported
through interface only. We will learn about interfaces later.
Darshan P R, Asst. Professor Page 1
JAVA –Unit2 PESIAMS,Shimoga
When one class inherits multiple classes, it is known as multiple
inheritance. For Example:
Single Inheritance Example
When a class inherits another class, it is known as a single
inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
Darshan P R, Asst. Professor Page 2
JAVA –Unit2 PESIAMS,Shimoga
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel
inheritance.
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...
Darshan P R, Asst. Professor Page 3
JAVA –Unit2 PESIAMS,Shimoga
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known
as hierarchical inheritance.
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...
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple
inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class
inherits A and B classes. If A and B classes have the same method
and you call it from child class object, there will be ambiguity to call
the method of A or B class.
Darshan P R, Asst. Professor Page 4
JAVA –Unit2 PESIAMS,Shimoga
Since compile-time errors are better than runtime errors, Java
renders compile-time error if you inherit 2 classes. So whether you
have same method or different, there will be compile time error.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
public static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Compile Time Error
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.
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).
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
Darshan P R, Asst. Professor Page 5
JAVA –Unit2 PESIAMS,Shimoga
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
Bike is running safely
Object class in Java
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.
Methods of Object class
The Object class provides many methods. They are as follows:
Method Description
public final Class returns the Class class object of this
getClass() object. The Class class can further be
used to get the metadata of this class.
public int hashCode() returns the hashcode number for this
object.
Darshan P R, Asst. Professor Page 6
JAVA –Unit2 PESIAMS,Shimoga
public String toString() returns the string representation of this
object.
public final void notify() wakes up single thread, waiting on this
object's monitor.
public final void wakes up all the threads, waiting on
notifyAll() this object's monitor.
protected void is invoked by the garbage collector
finalize()throws before object is being garbage
Throwable collected.
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform
a single action in different ways.
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.
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.
Darshan P R, Asst. Professor Page 7
JAVA –Unit2 PESIAMS,Shimoga
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();
}
}
Output:
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).
Darshan P R, Asst. Professor Page 8
JAVA –Unit2 PESIAMS,Shimoga
static binding
When type of the object is determined at compiled time(by the
compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static
binding.
Example of static binding
class Dog{
private void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Dog d1=new Dog();
d1.eat();
}
}
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();
}
Darshan P R, Asst. Professor Page 9
JAVA –Unit2 PESIAMS,Shimoga
}
Output:dog is eating...
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.
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.
List list = new ArrayList();
list.add(10);
list.add("10");
With Generics, it is required to specify the type of object we need to st
ore.
List<Integer> list = new ArrayList<Integer>();
list.add(10);
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.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.
Darshan P R, Asst. Professor Page 10
JAVA –Unit2 PESIAMS,Shimoga
List<String> list = new ArrayList<String>();
list.add("hello");
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.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error
Syntax to use generic collection
ClassOrInterface<Type>
Example to use Generics in java
ArrayList<String>
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
String s=list.get(1);//type casting is not required
System.out.println("element is: "+s);
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
Darshan P R, Asst. Professor Page 11
JAVA –Unit2 PESIAMS,Shimoga
}
}
} Output:
element is: jai
rahul
jai
Generic class
A class that can refer to any type is known as a generic class. Here,
we are using the T type parameter to create the generic class of
specific type.
Let's see a simple example to create and use the generic class.
Creating a generic class:
class MyGen<T>{
T obj;
void add(T obj){this.obj=obj;}
T get(){return obj;}
}
Generic Method
Like the generic class, we can create a generic method that can
accept any type of arguments. Here, the scope of arguments is
limited to the method where it is declared. It allows static as well as
non-static methods.
public class TestGenerics4{
public static < E > void printArray(E[] elements) {
for ( E element : elements){
System.out.println(element );
Darshan P R, Asst. Professor Page 12
JAVA –Unit2 PESIAMS,Shimoga
}
System.out.println();
}
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A' };
System.out.println( "Printing Integer Array" );
printArray( intArray );
System.out.println( "Printing Character Array" );
printArray( charArray );
}
Output
Printing Integer Array
10
20
30
40
50
Printing Character Array
J
A
V
A
Class Type Casting in Java
Typecasting is the assessment of the value of one primitive data type
to another type. In java, there are two types of casting namely
upcasting and downcasting as follows:
Upcasting is casting a subtype to a super type in an upward direction
to the inheritance tree.
Downcasting refers to the procedure when subclass type refers to the
object of the parent class is known as downcasting.
Darshan P R, Asst. Professor Page 13
JAVA –Unit2 PESIAMS,Shimoga
The following image illustrates the concept of upcasting and
downcasting:
From the above example we can observe the following points:
Syntax of Upcasting:
Parent p = new Child();
Upcasting will be done internally and due to upcasting the object is
allowed to access only parent class members and child class
specified members (overridden methods, etc.) but not all members.
// This variable is not
// accessible
p.id = 1;
Syntax of Downcasting:
Child c = (Child)p;
1. Downcasting has to be done externally and due to downcasting a
child object can acquire the properties of the parent object.
c.name = p.name;
i.e., c.name = "java"
Darshan P R, Asst. Professor Page 14
JAVA –Unit2 PESIAMS,Shimoga
Java instanceof
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
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
Output:true
Abstraction in Java
Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Darshan P R, Asst. Professor Page 15
JAVA –Unit2 PESIAMS,Shimoga
Abstract class in Java
A class which is declared with the abstract keyword is known as an
abstract class in Java. It can have abstract and non-abstract
methods (method with the body).
o An abstract class must be declared with an abstract keyword.
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.
Abstract Method in Java
A method which is declared as abstract and does not have
implementation is known as an abstract method.
Example of abstract method
abstract void printStatus();//no method body and abstract
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();
}
}
running safely
Darshan P R, Asst. Professor Page 16
JAVA –Unit2 PESIAMS,Shimoga
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.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
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?
o An interface is declared by using the interface keyword.
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default. }
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class,
an interface extends another interface, but a class implements an
interface.
Darshan P R, Asst. Professor Page 17
JAVA –Unit2 PESIAMS,Shimoga
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
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends
multiple interfaces, it is known as multiple inheritance.
Darshan P R, Asst. Professor Page 18
JAVA –Unit2 PESIAMS,Shimoga
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
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.
Darshan P R, Asst. Professor Page 19
JAVA –Unit2 PESIAMS,Shimoga
There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
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.
he package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
java.util
The basic utility classes required by the programmer are provided
by this #.
Class Description
AbstractQueue<E> The class is used for providing a rough
implementation of the Queue interface. The
class is declared as:
public abstract class AbstractQueue<E>
extends AbstractCollection<E>
implements Queue<E>
The class methods are extended from the
AbstractCollection class.
Darshan P R, Asst. Professor Page 20
JAVA –Unit2 PESIAMS,Shimoga
ArrayList<E> The class is used for providing a rough
implementation of the List interface. The class
is declared as:
public class ArrayList<E> extends
AbstractList<E>
implements List<E>, RandomAccess,
Cloneable, Serializable
The class methods are extended from the
AbstractList<E> class.
Arrays The class contains various methods which can
be used for the performing large number of
operations on arrays. The class is declared as:
public class Array extends Object
The class methods are extended from the
Objetct class.
BitSet A vector consisting of bits is created by this
class. The class is declared as:
public class BitSet extends Object
implements Cloneable, Serializable
The class methods are extended from the
Object class.
Calendar It is an abstract class for providing the date
time related conversions. The class is declared
as:
public class BitSet extends Object
implements Cloneable, Serializable
The class methods are extended from the
Object class.
Collections The class consists of various methods which is
used for performing of various operations on
collections in java. The class is declared as:
public class Collections extends Object
Darshan P R, Asst. Professor Page 21
JAVA –Unit2 PESIAMS,Shimoga
The class methods are extended from the
Object class.
Currency The class is used for the representation of
currency in various dominations.The class is
declared as:
public final class Currency extends Object
implements Serializable
The class methods are extended from the
Object class.
Date The class is used for representation of date.
The class is declared as:
public class Date extends Object
implements Serializable, Cloneable,
Comparable
The class methods are extended from the
Object class.
Dictionary<K,V> The following abstract class is a parent of
many. It is used for the mapping of key into
values. The class is declared as:
public abstract class Dictionary<K,V> extends
Object
The class methods are extended from the
Object class.
EnumMap,V> The class is a special implementation of Map
class designed for enum values. The class is
declared as:
public class EnumMap,V>
extends AbstractMap<K,V>
implements Serializable, Cloneable
The class methods are extended from the
AbstractMap<K,V> class.
Darshan P R, Asst. Professor Page 22
JAVA –Unit2 PESIAMS,Shimoga
EnumSet The class is used for providing a rough
implementation of the Set interface for the
enum values. The class is declared as:
public abstract class EnumSet
extends AbstractSet<E>
implements Cloneable, Serializable
The class methods are extended from the
AbstractSet<E> class.
EventObject All the objects of Event states are derived from
this class. The class is declared as:
public class EventObject extends Object
implements Serializable
The class methods are extended from the
Object class.
GregorianCalendar It is the child class of Calendar class. The class
is declared as:
public class GregorianCalendar
extends Calendar
The class methods are extended from the
Calendar class.
Hashtable<K,V> Hash table is implemented by this class. The
class is declared as:
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, Serializable
The class methods are extended from the
Dictionary<K,V> class.
IdentityHashMap<K The class is an implementation of the map
,V> interface for hash tables. The class is declared
as:
public class IdentityHashMap<K,V>
extends AbstractMap<K,V>
Darshan P R, Asst. Professor Page 23
JAVA –Unit2 PESIAMS,Shimoga
implements Map<K,V>, Serializable, Cloneable
The class methods are extended from the
AbstractMap class.
LinkedList<E> Interfaces such as List and Deque are
implemented by using doubly linked list. The
class is declared as:
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable,
Serializable
The class methods are extended from the
AbstractSequentialList<E>class.
ListResourceBundle The class is the successor of ResourceBundle
which is designed to make the resources
available to the locale. The class is declared as:
public abstract class ListResourceBundle
extends ResourceBundle
The class methods are extended from the
ResourceBundle class.
Locale It is used to reflect a region on space of any
type. The class is declared as:
public final class Locale extends Object
implements Cloneable, Serializable
The class methods are extended from the
Object class.
Locale.Builder Instances of the class are used to make the
Locale class objects. The class is declared as:
public static final class Locale.Builder
extends Object
The class methods are extended from the
Object class.
Darshan P R, Asst. Professor Page 24
JAVA –Unit2 PESIAMS,Shimoga
Objects The various methods of the class are used to
manipulate the number of operations to be
performed on objects. The class is declared as:
public class Objects extends Object
The class methods are extended from the
Object class.
Observable The objects that we can see, monitor or
observe are represented by this class. The class
is declared as:
public class Observable extends Object
The class methods are extended from the
Object class.
PriorityQueue<E> The class represents a priority queue. It is a
data structure in which each element has a
assigned priority with it. The class is declared
as:
public class PriorityQueue<E> extends
AbstractQueue<E>
implements Serializable
The class methods are extended from the
AbstractQueue<E> class.
Properties A wide set of properties are defined by this
class. The class is declared as:
public class Properties
extends Hashtable<Object,Object>
The class methods are extended from the
Hashtable<Object,Object> class.
Scanner It is a very important utility class which is used
to add user defined values to the class. The
class is declared as:
public final class Scanner
extends Object
Darshan P R, Asst. Professor Page 25
JAVA –Unit2 PESIAMS,Shimoga
implements Iterator, Closeable
The class methods are extended from the
Object class.
Timer The class provides facility of scheduling of
tasks. The class is declared as:
public class Timer
extends Object
The class methods are extended from the
Object class.
TimeZone The instances of the class represent the offset
of the time zone. The class is declared as:
public abstract class TimeZone
extends Object
implements Serializable, Cloneable
The class methods are extended from the
Object class.
Vector<E> The class represents an array of object which
can further also be extended. The class is
declared as:
public class Vector<E> extends
AbstractList<E>
implements List<E>, RandomAccess,
Cloneable, Serializable
The class methods are extended from the
AbstractList<E> class.
Darshan P R, Asst. Professor Page 26