You are on page 1of 71

1

Uniti2 -- Inheritane
1.introduction

1.1 inheritance hierarchy

1.2 types of inheritances

1.3 super class and sub class

1.4 member acces rules

1.5 super keyword

1.6 preventing inheritance : (using final classes and methods)

1.7 Object class and its methods

2. polymorphism

2.1 Runtime polymorphism

2.2 Dynamic Binding

2.3 Method Overriding

3. Abstract Class and Abstract methods

3.1 Difference b/w Abstract class and concrete class

4. Interfaces

4.1 Defining Interfaces

4.2 Difference b/w class and interface

4.3 Abstract class vs interface

4.5 accessing implementation through interface reference.


2

4.6 Extending interface

5. inner classes

5.1 concept of inner classes

5.2 uses of inner classes

5.3 Types of inner classes

6. packages

6.1 Defining a package

6.2 creating and accessing a package

6.3 understanding a Package

6.4 importing a package


3

1.introduction of inheritance
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.

Syntax
class Super
{
.....
.....
}

class Sub extends Super


{
.....
.....
}

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).

o For Code Reusability.

Terms 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.
4

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


1. class Subclass-name extends Superclass-name  
2. {  
3.    //methods and fields  
4. }  

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass,


and the new class is called child or subclass.

Java Inheritance Example


5

As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee.
It means that Programmer is a type of Employee.

1. class Employee{  
2.  float salary=40000;  
3. }  
4. class Programmer extends Employee{  
5.  int bonus=10000;  
6.  public static void main(String args[])
7. {  
8.    Programmer p=new Programmer();  
9.    System.out.println("Programmer salary is:"+p.salary);  
10.   System.out.println("Bonus of Programmer is:"+p.bonus);  
11.}  
12.}  
Programmer salary is:40000.0

Bonus of programmer is:10000

1.1 inheritance hierarchy


With the use of inheritance the information is made manageable in a hierarchical
order.

If you have multiple subclasses that inherit from a superclass, you can form an inheritance
hierarchy. Every subclass is-a or is a kind of the superclass. For example, here is an
inheritance hierarchy of Shapes. Square is-a Rectangle and a subclass of Rectangle.
Rectangle is-a Shape and a subclass of Shape. In Java, the class Object is at the top of
hierarchy. Every class in Java inherits from Object and is-an Object.

Figure 1: An Inheritance Hierarchy of Shapes


6

1.2 Types of inheritances


1.Single Inheritance: In single inheritance, subclasses inherit the features of one
superclass. In the image below, class A serves as a base class for the derived class B.

2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting


a base class and as well as the derived class also act as the base class to other class.
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.

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 class B, C
7

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 interface A and B.

5. Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the


above types of inheritance. Since java doesn’t support multiple inheritances
with classes, hybrid inheritance is also not possible with classes. In java, we
can achieve hybrid inheritance only through Interfaces.

 
8

Note: there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through
interface only. We will learn about interfaces later.

Important facts about inheritance in Java 


 Default superclass: Except Object class, which has no superclass, every class
has one and only one direct superclass (single inheritance). In the absence of any
other explicit superclass, every class is implicitly a subclass of the Object class.

 Superclass can only be one: A superclass can have any number of subclasses.
But a subclass can have only one superclass. This is because Java does not
support multiple inheritances  with classes. Although with interfaces, multiple
inheritances are supported by java.

 Inheriting Constructors: A subclass inherits all the members (fields, methods,


and nested classes) from its superclass. Constructors are not members, so they
are not inherited by subclasses, but the constructor of the superclass can be
invoked from the subclass.

note: if super class has parameterized constructor it should be called from child
class constructor other wise we get compile time error

 Private member inheritance: A subclass does not inherit the private members
of its parent class. However, if the superclass has public or protected methods(like
getters and setters) for accessing its private fields, these can also be used by the
subclass.

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

1. class Animal{  
2. void eat()
3. {
9

4. System.out.println("eating...");
5. }  
6. }  
7. class Dog extends Animal{  
8. void bark()
9. {
10.System.out.println("barking...");
11.}  
12.}  
13.class TestInheritance{  
14.public static void main(String args[])
15.{  
16.Dog d=new Dog();  
17.d.bark();  
18.d.eat();  
19.}}  

Output:

barking...
eating...

Multilevel Inheritance Example


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.

File: TestInheritance2.java

1. class Animal{  
2. void eat()
3. {
4. System.out.println("eating...");
5. }  
6. }  
7. class Dog extends Animal{  
8. void bark()
10

9. {
10.System.out.println("barking...");
11.}  
12.}  
13.class BabyDog extends Dog{  
14.void weep()
15.{
16.System.out.println("weeping...");
17.}  
18.}  
19.class TestInheritance2{  
20.public static void main(String args[]){  
21.BabyDog d=new BabyDog();  
22.d.weep();  
23.d.bark();  
24.d.eat();  
25.}}  

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


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.

File: TestInheritance3.java

1. class Animal{  
2. void eat(){System.out.println("eating...");}  
3. }  
4. class Dog extends Animal{  
5. void bark()
6. {
7. System.out.println("barking...");
11

8. }  
9. }  
10.class Cat extends Animal{  
11.void meow()
12.{
13.System.out.println("meowing...");
14.}  
15.}  
16.class TestInheritance3
17.{  
18.public static void main(String args[]){  
19.Cat c=new Cat();  
20.c.meow();  
21.c.eat();  
22.//c.bark();//C.T.Error  
23.}}  

Output:

meowing...
eating...

Q) 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.

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.

1. class A{  
2. void msg(){System.out.println("Hello");}  
3. }  
12

4. class B{  
5. void msg(){System.out.println("Welcome");}  
6. }  
7. class C extends A,B{//suppose if it were  
8.    
9.  public static void main(String args[]){  
10.   C obj=new C();  
11.   obj.msg();//Now which msg() method would be invoked?  
12.}  
13.}  

1.3 super class and sub class


Inheritance is one of the main features of programming in Java. It is a mechanism in
which one or more classes acquire the properties of another class.

The class which inherits the properties of another class is called the subclass or
the child class. The class whose properties are inherited is known as the base class,
super class  or the parent class.

The variables and methods by  using Java Access Modifiers implements reusability of
existing code

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.

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

1.4 member acces rules or access modifiers in


inheritance

…….

….
13

1.5 super keyword


The super keyword refers to superclass (parent) objects.

It is used to call superclass methods, and to access the superclass constructor.

The most common use of the super keyword is to eliminate the confusion between


superclasses and subclasses that have methods with the same name.

The super keyword in Java is a reference variable which is used to refer immediate


parent class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.

2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance variable .

We can use super keyword to access the data member or field of parent class. It is
used if parent class and child class have same fields.

1. class Animal{  
2. String color="white";  
3. }  
4. class Dog extends Animal{  
5. String color="black";  
6. void printColor()
7. {  
8. System.out.println(color);//prints color of Dog class  
9. System.out.println(super.color);//prints color of Animal class  
10.}  
11.}  
12.class TestSuper1{  
13.public static void main(String args[]){  
14.Dog d=new Dog();  
14

15.d.printColor();  
16.}}  
Test it Now

Output:

black
white

In the above example, Animal and Dog both classes have a common property color. If
we print color property, it will print the color of current class by default. To access the
parent property, we need to use super keyword.

2) super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method
is overridden.

1. class Animal{  
2. void eat()
3. {
4. System.out.println("eating...");
5. }  
6. }  
7. class Dog extends Animal
8. {  
9. void eat()
10.{
11.System.out.println("eating bread...");
12.}  
13.void bark()
14.{
15.System.out.println("barking...");
16.}  
17.void work()
18.{  
19.super.eat();  
20.bark();  
15

21.}  
22.}  
23.class TestSuper2{  
24.public static void main(String args[]){  
25.Dog d=new Dog();  
26.d.work();  
27.}}  
Test it Now

Output:

eating...
barking...

In the above example Animal and Dog both classes have eat() method if we call eat()
method from Dog class, it will call the eat() method of Dog class by default because
priority is given to local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor. Let's see a
simple example:

1. class Animal{  
2. Animal()
3. {
4. System.out.println("animal is created");
5. }  
6. }  
7. class Dog extends Animal{  
8. Dog(){  
9. super();  
10.System.out.println("dog is created");  
11.}  
12.}  
13.class TestSuper3{  
14.public static void main(String args[]){  
16

15.Dog d=new Dog();  
16.}}  
Test it Now

Output:

animal is created
dog is created
Note: super() is added in each class constructor automatically by compiler if there is
no super() or this().

As we know well that default constructor is provided by compiler automatically if there


is no constructor. But, it also adds super() as the first statement.

Another example of super keyword where super() is provided by the compiler


implicitly.

1. class Animal{  
2. Animal()
3. {
4. System.out.println("animal is created");
5. }  
6. }  
7. class Dog extends Animal{  
8. Dog()
9. {  
10.System.out.println("dog is created");  
11.}  
12.}  
13.class TestSuper4{  
14.public static void main(String args[]){  
15.Dog d=new Dog();  
17

16.}}  
Test it Now

Output:

animal is created
dog is created
What if the child class is not overriding any method: No need of
super

When child class doesn’t override the parent class method then we don’t need to use the
super keyword to call the parent class method. This is because in this case we have only
one version of each method and child class has access to the parent class methods so we
can directly call the methods of parent class without using super.

class Parentclass
{
void display(){
System.out.println("Parent class method");
}
}
class Subclass extends Parentclass
{
void printMsg(){
/* This would call method of parent class,
* no need to use super keyword because no other
* method with the same name is present in this class
*/
display();
}
public static void main(String args[]){

Subclass obj= new Subclass();


obj.printMsg();
}
}
Output:

Parent class method

1.6 preventing inheritance : (using final classes


and methods)

final keyword is used in different contexts. First of all, final is a non-access


modifier applicable only to a variable, a method or a class.Following are different
contexts where final is used.
18

The final keyword in java is used to restrict the user. The java final keyword can be
used in many context. Final can be:

1. variable

2. method

3. class

The final keyword can be applied with the variables, a final variable that have no value
it is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in
the static block only. We will have detailed learning of these. Let's first learn the basics
of final keyword.

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will
be constant).
19

Initializing a final variable :


We must initialize a final variable, otherwise compiler will throw compile-time error.A
final variable can only be initialized once, either via an initializer or an assignment
statement. There are three ways to initialize a final variable :

1. You can initialize a final variable when it is declared.This approach is the most
common. A final variable is called blank final variable,if it is not initialized while
declaration. Below are the two ways to initialize a blank final variable.

2. A blank final variable can be initialized inside instance-initializer block  or inside


constructor. If you have more than one constructor in your class then it must be
initialized in all of them, otherwise compile time error will be thrown.

3. A blank final static variable can be initialized inside static block.

blank or uninitialized final variable


A final variable that is not initialized at the time of declaration is known as blank final
variable.

If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an
employee.

It can be initialized in constructors and in instance block.

Example of blank final variable


1. class Student
2. {  
3. int id;  
4. String name;  
5. final String PAN_CARD_NUMBER;  
6. ...  
7. }  
Que) Can we initialize blank final variable?

Yes, but in constructor or in method. For example:

1. class Bike10
2. {  
3.   final int speedlimit;//blank final variable  
4.     
20

5.   Bike10()
6. {  
7.   speedlimit=70;  
8.   System.out.println(speedlimit);  
9.   }  
10.  
11.  public static void main(String args[]){  
12.    new Bike10();  
13. }  
14.}  
Test it Now

Output: 70
Example—2 : initializing final varible either in constructor or in instance
block

class Bike
{
final int speedlimit;//blank final variable
final int BREAKS;// blank final variable

{
BREAKS= 3;
}
Bike()
{
speedlimit=70;
System.out.println(speedlimit);
}
Bike(int x)
{
speedlimit=70;
}

public static void main(String args[]){


Bike b= new Bike();
}
}

static blank final variable


A static final variable that is not initialized at the time of declaration is known as static
blank final variable. It can be initialized only in static block.
21

Example of static blank final variable


1. class A{  
2.   static final int data;//static blank final variable  
3.   static{ 
4. data=50;
5. }  
6.   public static void main(String args[]){  
7.     System.out.println(A.data);  
8.  }  
9. }  
Q) Can we declare a constructor final?

No, because constructor is never inherited.

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable,
but It can't be changed because final variable once assigned a value can never be
changed.

1. class Bike9
2. {  
3.  final int speedlimit=90;//final variable  
4.  void run()
5. {  
6.   speedlimit=400;  
7.  }  
8.  public static void main(String args[])
9. {  
10. Bike9 obj=new  Bike9();  
11. obj.run();  
12. }  
13.}//end of class  
Test it Now

Output:Compile Time Error


22

2) Java final method


If you make any method as final, you cannot override it.

When a method is declared with final keyword, it is called a final method. A final


method cannot be overridden. The Object class does this—a number of its methods
are final.We must declare methods with final keyword for which we required to follow
the same implementation throughout all the derived classes . 

Example of final method


1. class Bike{  
2.   final void run()
3. {
4. System.out.println("running");}  
5. }  
6.      
7. class Honda extends Bike{  
8.    void run()
9. {
10.System.out.println("running safely with 100kmph");
11.}  
12.     
13.   public static void main(String args[]){  
14.   Honda honda= new Honda();  
15.   honda.run();  
16.   }  
17.}  
Test it Now

Output:Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.

When a class is declared with final keyword, it is called a final class. A final class


cannot be extended(inherited).

There are two uses of a final class :


23

One is definitely to prevent inheritance, as final classes cannot be extended. For


example, all Wrapper Classes like Integer,Float etc. are final classes. We can not
extend them.

1. final class A
2. {
3. // methods and fields
4. }
5. // The following class is illegal.
6. class B extends A
7. {
8. // COMPILE-ERROR! Can't subclass A
9. }
The other use of final with classes is to create an immutable class  like the
predefined String class.You can not make a class immutable without making it final.
Example of final class
1. final class Bike
2. {
3. }  
4.   
5. class Honda1 extends Bike
6. {  
7.   void run()
8. {
9. System.out.println("running safely with 100kmph");
10.}  
11.    
12.  public static void main(String args[]){  
13.  Honda1 honda= new Honda1();  
14.  honda.run();  
15.  }  
16.}  
Test it Now

Output:Compile Time Error


24

1.7 Object class and its methods


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.

Object class is present in java.lang package.

Every class in Java is directly or indirectly derived from the Object class. If a Class


does not extend any other class then it is direct child class of Object and if extends
other class then it is an indirectly derived.

Therefore the Object class methods are available to all Java classes. Hence Object
class acts as a root of inheritance hierarchy in any Java Program.

Methods of Object class


The Object class provides many methods. They are as follows:

Method Description

public final Class getClass() returns the Class class object of this 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.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone) of this
CloneNotSupportedException object.

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 notifyAll() wakes up all the threads, waiting on this object's
monitor.

public final void wait(long causes the current thread to wait for the specified
25

timeout)throws milliseconds, until another thread notifies (invokes


InterruptedException notify() or notifyAll() method).

public final void wait(long causes the current thread to wait for the specified
timeout,int nanos)throws milliseconds and nanoseconds, until another thread
InterruptedException notifies (invokes notify() or notifyAll() method).

public final void wait()throws causes the current thread to wait, until another
InterruptedException thread notifies (invokes notify() or notifyAll()
method).

protected void finalize()throws is invoked by the garbage collector before object is


Throwable being garbage collected.
Using Object class methods

There are methods in Object class:

1. toString() :

toString() provides String representation of an Object and used to convert an


object to String.
The default toString() method for class Object returns a string consisting of the
name of the class of which the object is an instance, the at-sign character `@’,
and the unsigned hexadecimal representation of the hash code of the object. In
other words, it is defined as:

Default behavior of toString() is to print class name, then


// @, then unsigned hexadecimal representation of the hash code of the object
2. public String toString()
3. {
4. return getClass().getName() + "@" +
Integer.toHexString(hashCode());
5. }

It is always recommended to override toString() method to get our own String


representation of Object.
Note : Whenever we try to print any Object reference, then internally toString()
method is called.
Student s = new Student();
26

// Below two statements are equivalent


System.out.println(s);
System.out.println(s.toString());

hashCode() :

For every object, JVM generates a unique number which is hashcode. It returns
distinct integers for distinct objects.
A common misconception about this method is that hashCode() method returns
the address of object, which is not correct.

It convert the internal address of object to an integer by using an algorithm.

The hashCode() method is native because in Java it is impossible to find address


of an object, so it uses native languages like C/C++ to find address of the object.

Use of hashCode() method : 

Returns a hash value that is used to search object in a collection. JVM(Java Virtual
Machine) uses hashcode method while saving objects into hashing related data
structures like HashSet, HashMap, Hashtable etc. The main advantage of saving
objects based on hash code is that searching becomes easy.

Note : Override of hashCode() method needs to be done such that for every


object we generate a unique number. For example,for a Student class we can
return roll no. of student from hashCode() method as it is unique.

Java program to demonstrate working of hasCode() and toString()

public class Student


{
static int last_roll = 100;

int roll_no;

Student()
{
roll_no = last_roll;
last_roll++;
}

public int hashCode()


{
27

return roll_no;
}
/*public String toString()
{
return "Mystudent"+hashCode();
}
*/
public static void main(String args[])
{
Student s1 = new Student();
Student s2 = new Student();
// Below two statements are equivalent
System.out.println(s1);
System.out.println(s1.toString());
System.out.println(s2);
System.out.println(s2.toString());
}
}

Output :
Student@64
Student@64
Student@65

equals(Object obj) :
this method compare the reference addresses of two objects. if two objects
adresse are same then it return true otherwise it return false

example:
public class EqualDemo
{
public static void main(String[] args)
{

EqualDemo d1= new EqualDemo();


EqualDemo d2= new EqualDemo();

System.out.println(d1.equals(d2));
}
}

output: false

getClass() :
28

We can use this class object to get Class level information.i.e meta data of a class

Returns the class object of “this” object and used to get actual runtime class of
the object.

Java program to demonstrate working of getClass()

public class GetclassDemo


{
static int x=10;
public static void main(String[] args)
{
GetclassDemo d= new GetclassDemo();
Class c=d.getClass();
System.out.println(d.hashCode());
System.out.println(c);

System.out.println(c.getName());
System.out.println(c.getModifiers());
System.out.println(c.hashCode());
}

Output:
2018699554
class classroom.GetclassDemo
classroom.GetclassDemo
1
1829164700

Note :After loading a .class file, JVM will create an object of the
type java.lang.Class in the Heap area. We can use this class object to get Class
level information. It is widely used in Reflection

finalize() method :

This method is called just before an object is garbage collected. It is called by


the Garbage Collector on an object when garbage collector determines that there
are no more references to the object.
29

We should override finalize() method to dispose system resources, perform clean-


up activities and minimize memory leaks.

For example before destroying Servlet objects web container, always called finalize
method to perform clean-up activities of the session.

Note :finalize method is called just once on an object even though that object is
eligible for garbage collection multiple times.

Java program to demonstrate working of finalize()

public class Test


{
public static void main(String[] args)
{
Test t1 = new Test();
Test t2 = new Test();
System.out.println(t1.hashCode());
System.out.println(t2.hashCode());

t1 = null;
t2 = null;

// calling garbage collector


System.gc();

System.out.println("end of the program");


System.out.println(t1.hashCode());
System.out.println(t2.hashCode());
}
//Override
protected void finalize()
{
System.out.println("finalize method called");
}
}

Output:
2018699554
1311053135
30

end of the program


finalize method called
finalize method called
Exception in thread "main" java.lang.NullPointerException
at classroom.Test.main(Test.java:19)

clone() :
It returns a new object that is exactly the same as this object. For clone() method
refer Clone()

The remaining three methods wait(), notify() notifyAll() are related to


Concurrency.

2. polymorphism
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.

There are two types of polymorphism in java:


1) Static Polymorphism also known as compile time polymorphism
2) Dynamic Polymorphism also known as runtime polymorphism
31

Compile time Polymorphism (or Static polymorphism)


compile time polymorphism is nothing but the compiler will decide which method is called at
compile time.

so Polymorphism that is resolved during compiler time is known as static polymorphism.


Method overloading is an example of compile time polymorphism.
32

Method Overloading: This allows us to have more than one method having the same
name, if the parameters of methods are different in number, sequence and data types of
parameters. We have already discussed Method overloading here:

Example of static Polymorphism


Method overloading is one of the way java supports static polymorphism. Here we have two
definitions of the same method add() which add method would be called is determined by
the parameter list at the compile time. That is the reason this is also known as compile time
polymorphism.

class SimpleCalculator
{
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}
}
public class Demo
{
public static void main(String args[])
{
SimpleCalculator obj = new SimpleCalculator();

System.out.println(obj.add(10, 20));// here which method is


called is decided by compiler.
System.out.println(obj.add(10, 20, 30));
}
}

Output:

30
60
33

2.1 Runtime polymorphism


rutime polymorphism is nothing but which method is called is decided by javm at run
time.

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:

1. class A{}  
2. class B extends A{}  
1. A a=new B();//upcasting  

For upcasting, we can use the reference variable of class type or an interface type. For
Example:

1. interface I{}  
2. class A{}  
3. class B extends A implements I{}  

Here, the relationship of B class would be:


34

B IS-A A
B IS-A I
B IS-A Object

Since Object is the root class of all classes in Java, so we can write 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.

1. class Bike{  
2.   void run()
3. {
4. System.out.println("running");
5. }  
6. }  
7. class Splendor extends Bike{  
8.   void run()
9. {
10.System.out.println("running safely with 60km");
11.}  
12.  
13.  public static void main(String args[]){  
14.    Bike b = new Splendor();//upcasting  
15.    b.run();  
16.  }  
17.}  
Test it Now

Output:

running safely with 60km.


35

2.2.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).

Understanding Type
Let's understand the type of instance.

1) variables have a type

Each variable has a type, it may be primitive and non-primitive.

1. int data=30;  

Here data variable is a type of int.

2) References have a type


1. class Dog{  
2.  public static void main(String args[]){  
3.   Dog d1;//Here d1 is a type of Dog  
4.  }  
5. }  
3) Objects have a type
An object is an instance of particular java class,but it is also an instance of its superclass.

1. class Animal{}  
2.   
3. class Dog extends Animal
4. {  
5.  public static void main(String args[])
6. {  
7.   Dog d1=new Dog();  
36

8.  }  
9. }  
Here d1 is an instance of Dog class, but it is also an instance of Animal.

2.2.1 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


1. class Animal{  
2.  private void eat()
3. {
4. System.out.println("animal is eating...");}  
5.   
6.  public static void main(String args[]){  
7.   Animal a1=new Animal();  
8.   a1.eat();  
9.  }  
10.}  
output : dog is eating

2.2.2 Dynamic binding


When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding


1. class Animal{  
2.  void eat()
3. {
4. System.out.println("animal is eating...");
5. }  
6. }  
7.   
37

8. class Dog extends Animal{  
9.  void eat()
10.{
11.System.out.println("dog is eating...");}  
12.  
13. public static void main(String args[]){  
14.  Animal a=new Dog();  
15.  a.eat();  
16. }  
17.}  
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.

2.3 Method Overriding


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.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
o Method overriding is used for runtime polymorphism

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).

 
38

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.

1. //Java Program to demonstrate why we need method overriding  
2. //Here, we are calling the method of parent class with child  
3. //class object.  
4. //Creating a parent class  
5. class Vehicle
6. {  
7.   void run()
8. {
9. System.out.println("Vehicle is running with 40 km");
10.}  
11.}  
12.//Creating a child class  
13.class Bike extends Vehicle
14.{  
15.  public static void main(String args[])
16.{  
17.  //creating an instance of child class  
18.  Bike obj = new Bike();  
19.  //calling the method with child class instance  
20.  obj.run();  
21.  }  
22.}  
Test it Now

Output:

Vehicle is running with 40 km

Problem is that I have to provide a specific implementation of run() method in subclass


that is why we use method overriding.
39

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation.

The name and parameter of the method are the same, and there is IS-A relationship
between the classes, so there is method overriding.

1. //Java Program to illustrate the use of Java Method Overriding  
2. //Creating a parent class.  
3. class Vehicle{  
4.   //defining a method  
5.   void run()
6. {
7. System.out.println("Vehicle is running");
8. }  
9. }  
10.//Creating a child class  
11.class Bike2 extends Vehicle
12.{  
13.  //defining the same method as in the parent class  
14.  void run()
15.{
16.System.out.println("Bike is running safely with 60 km");
17.}  
18.  
19.  public static void main(String args[]){  
20.  Bike2 obj = new Bike2();//creating object  
21.  obj.run();//calling method  
22.  }  
23.}  
Test it Now

Output:

Bike is running safely with 60 km


40

Difference between method overloading and method overriding in java


There are many differences between method overloading and method overriding in
java. A list of differences between method overloading and method overriding are given
below:

No Method Overloading Method Overriding


.

1) Method overloading is used to Method overriding is used to provide the


increase the readability of the specific implementation of the method
program. that is already provided by its super
class.

2) Method overloading is Method overriding occurs in two


performed within class. classes that have IS-A (inheritance)
relationship.

3) In case of method In case of method overriding, parameter


overloading, parameter must be must be same.
different.

4) Method overloading is the example Method overriding is the example of run


of compile time polymorphism. time polymorphism.

5) Return type can be same or Return type must be same or


different in method overloading. But covariant in method overriding.
you must have to change the
parameter.
41

3. Abstract Class and Abstract methods


Before learning the Java abstract class, let's understand the abstraction in Java first

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.

Another way, it shows only essential things to the user and hides the internal details,
for example, sending SMS where you type the text and send the message. You don't
know the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)

2. Interface (100%)

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have
abstract methods or concrete methods(method with body) and non-abstract
methods(method without body). It needs to be extended and its method implemented.
It cannot be instantiated.

Abstract class declaration

An abstract class outlines the methods but not necessarily implements all the methods.

//Declaration using abstract keyword


abstract class A
{
//This is abstract method
abstract void myMethod();

//This is concrete method with body


void anotherMethod()
{
//Does something
}
42

Points to Remember
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.

Rules

1: when it is difficult or often unnecessary to implement all the methods in parent class.
In these cases, we can declare the parent class as abstract, which makes it a special
class which is not complete on its own.

A class derived from the abstract class must implement all those methods that are
declared as abstract in the parent class.

2: Abstract class cannot be instantiated which means you cannot create the object of it.
To use this class, you need to create another class that extends this class and provides
the implementation of abstract methods, then you can use the object of that child class
to call non-abstract methods of parent class as well as implemented methods(those
that were abstract in parent but implemented in child class).

3: If a child does not implement all the abstract methods of abstract parent class, then
the child class must need to be declared abstract as well.

Do you know? Since abstract class allows concrete methods as well, it does not
provide 100% abstraction. You can say that it provides partial abstraction. Abstraction
is a process where you show only “relevant” data and “hide” unnecessary details of an
object from the user.

Why can’t we create the object of an abstract class?

Because these classes are incomplete, they have abstract methods that have no body
so if java allows you to create object of this class then if someone calls the abstract
method using that object then What would happen?
43

There would be no actual implementation of the method to invoke.


Also because an object is concrete. An abstract class is like a template, so you have to
extend it and build on it before you can use it.

Example of abstract class

1. abstract class A{}  

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

1. abstract void printStatus();//no method body and abstract  

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.

1. abstract class Bike
2. {  
3.   abstract void run();  
4. }  
5. class Honda4 extends Bike
6. {  
7. void run()
8. {
9. System.out.println("running safely");
10.}  
11.public static void main(String args[]){  
12. Bike obj = new Honda4();  
13. obj.run();  
14.}  
15.}  
Test it Now
44

running safely

3.1 Difference b/w Abstract class and concrete class

Sr. Key Abstract Class Concrete Class


No.

Supported Abstract class can have both an A concrete class can only have
Methods abstract as well as concrete methods. concrete methods. Even a single
1
abstract method makes the class
abstract.

Instantiation Abstract class can not be instantiated Concrete class can be instantiated
2
using new keyword. using new keyword.

Abstract Abstract class may or may not have Concrete clas can not have an
3
method abstract methods. abstract method.

Final Abstract class can not be declared as Concrete class can be declared
4
a final class. final.

Keyword Abstract class declared using abstract Concrete class is not having
5 keyword. abstract keyword during
declaration.

Inheritance Abstract class can inherit another Interface can inherit only an
6 class using extends keyword and inteface.
implement an interface.

Interface Abstract class can not implement an Interface can be implemented


interface alone. A child class is easily.
7
needed to be able to use the interface
for instantiation.
45

4. 1 Interfaces
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.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

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:
1. interface <interface_name>{  
2.       
3.     // declare constant fields  
46

4.     // declare methods that abstract   
5.     // by default.  
6. }  
However, an interface is different from a class in several ways, including −
 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces

Java 8 Interface Improvement


Since Java 8, interface can have default and static methods which is discussed later.

Internal addition by the compiler


The Java compiler adds public and abstract keywords before the interface method.
Moreover, it adds public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods
are public and abstract.

Java Interface Example: Bank


Let's see another example of java interface which provides the implementation of Bank
interface.

File: TestInterface2.java
47

1. interface Bank{  
2. float rateOfInterest();  
3. }  
4. class SBI implements Bank{  
5. public float rateOfInterest(){return 9.15f;}  
6. }  
7. class PNB implements Bank{  
8. public float rateOfInterest(){return 9.7f;}  
9. }  
10.class TestInterface2{  
11.public static void main(String[] args){  
12.Bank b=new SBI();  
13.System.out.println("ROI: "+b.rateOfInterest());  
14.}}  
Test it Now

Output:

ROI: 9.15

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it
is known as multiple inheritance.

1. interface Printable{  
2. void print();  
48

3. }  
4. interface Showable{  
5. void show();  
6. }  
7. class A7 implements Printable,Showable{  
8. public void print(){System.out.println("Hello");}  
9. public void show(){System.out.println("Welcome");}  
10.  
11.public static void main(String args[]){  
12.A7 obj = new A7();  
13.obj.print();  
14.obj.show();  
15. }  
16.}  
Test it Now

Output:Hello
Welcome

Q) Multiple inheritance is not supported through class in


java, but it is possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported
in the case of class because of ambiguity. However, it is supported in case of an
interface because there is no ambiguity. It is because its implementation is provided by
the implementation class. For example:

1. interface Printable{  
2. void print();  
3. }  
4. interface Showable{  
5. void print();  
6. }  
7.   
8. class TestInterface3 implements Printable, Showable{  
9. public void print(){System.out.println("Hello");}  
10.public static void main(String args[]){  
11.TestInterface3 obj = new TestInterface3();  
49

12.obj.print();  
13. }  
14.}  
Test it Now

Output:

Hello

As you can see in the above example, Printable and Showable interface have same
methods but its implementation is provided by class TestTnterface1, so there is no
ambiguity.

Interface inheritance
A class implements an interface, but one interface extends another interface.

1. interface Printable{  
2. void print();  
3. }  
4. interface Showable extends Printable{  
5. void show();  
6. }  
7. class TestInterface4 implements Showable{  
8. public void print(){System.out.println("Hello");}  
9. public void show(){System.out.println("Welcome");}  
10.  
11.public static void main(String args[]){  
12.TestInterface4 obj = new TestInterface4();  
13.obj.print();  
14.obj.show();  
15. }  
16.}  
Test it Now

Output:

Hello
50

Welcome

Java 8 Default Method in Interface//out of syllabus


Since Java 8, we can have method body in interface. But we need to make it default
method. Let's see an example:

File: TestInterfaceDefault.java

1. interface Drawable{  
2. void draw();  
3. default void msg(){System.out.println("default method");}  
4. }  
5. class Rectangle implements Drawable{  
6. public void draw(){System.out.println("drawing rectangle");}  
7. }  
8. class TestInterfaceDefault{  
9. public static void main(String args[]){  
10.Drawable d=new Rectangle();  
11.d.draw();  
12.d.msg();  
13.}}  
Test it Now

Output:

drawing rectangle
default method

Java 8 Static Method in Interface//out of syllabus


Since Java 8, we can have static method in interface. Let's see an example:

File: TestInterfaceStatic.java

1. interface Drawable{  
2. void draw();  
3. static int cube(int x){return x*x*x;}  
4. }  
5. class Rectangle implements Drawable{  
6. public void draw(){System.out.println("drawing rectangle");}  
51

7. }  
8.   
9. class TestInterfaceStatic{  
10.public static void main(String args[]){  
11.Drawable d=new Rectangle();  
12.d.draw();  
13.System.out.println(Drawable.cube(3));  
14.}}  
Test it Now

Output:

drawing rectangle
27

Q) What is marker or tagged interface?//out of


syllabus
An interface which has no member is known as a marker or tagged interface, for
example, Serializable, Cloneable, Remote, etc. They are used to provide some essential
information to the JVM so that JVM may perform some useful operation.

1. //How Serializable interface is written?  
2. public interface Serializable{  
3. }  

Nested Interface in Java


Note: An interface can have another interface which is known as a nested interface. We
will learn it in detail in the nested classes chapter. For example:

1. interface printable{  
2.  void print();  
3.  interface MessagePrintable{  
4.    void msg();  
5.  }  
6. }  
52

4.2 Difference b/w class and interface


Following are the important differences between Class and an Interface.

Sr. Key Class Interface


No.

Supported A class can have both an Interface can have only abstract
1 Methods abstract as well as concrete methods. Java 8 onwards, it can have
methods. default as well as static methods.

Multiple Multiple Inheritance is not Interface supports Multiple


2
Inheritance supported. Inheritance.

Supported final, non-final, static and non- Only static and final variables are
3
Variables static variables supported. permitted.

Implementation A class can implement an Interface can not implement an


4
interface. interface, it can extend an interface.

Keyword A class is declared using class Interface is declared using interface


5
keyword. keyword.

Inheritance A class can inherit another Interface can inherit only an inteface.
6 class using extends keyword
and implement an interface.

Inheritance A class can be inherited using Interface can only be implemented


7
extends keyword. using implements keyword.

Access A class can have any type of Interface can only have public
8
members like private, public. members.

9 Constructor A class can have constructor Interface can not have a constructor.
53

Sr. Key Class Interface


No.

methods.

4.3 Abstract class vs interface


.

Abstract class Interface

1) Abstract class can have abstract Interface can have only abstract methods.


and non-abstract methods. Since Java 8, it can have default and
static methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables.
variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

5) The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.

6) An abstract class can extend An interface can extend another Java


another Java class and implement interface only.
multiple Java interfaces.

7) An abstract class can be extended An interface can be implemented using


using keyword "extends". keyword "implements".
54

8) A Java abstract class can have Members of a Java interface are public by


class members like private, protected, default.
etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

4.4 implementing interfaces

4.5 accessing implementation through interface


reference.

public void topSpeed()

System.out.println("Audi : 250 km/h");

class Ford implements Speed {

public void topSpeed()

System.out.println("Ford : 220 km/h");

}
55

class BMW implements Speed {

public void topSpeed()

System.out.println("BMW : 300 km/h");

public class Javaapp {

public static void main(String[] args) {

Speed spd = new Audi();

spd.topSpeed();

spd = new Ford();

spd.topSpeed();

spd = new BMW();

spd.topSpeed();

}
56

4.6 Extending interface


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.

In java, an interface can extend another interface. When an interface wants to extend
another interface, it uses the keyword extends. The interface that extends another
interface has its own members and all the members defined in its parent interface too.

The class which implements a child interface needs to provide code for the methods defined
in both child and parent interfaces, otherwise, it needs to be defined as abstract class.
🔔 An interface can extend another interface.
🔔 An interface can not extend multiple interfaces.
🔔 An interface can implement neither an interface nor a class.
🔔 The class that implements child interface needs to provide code for all the methods
defined in both child and parent interfaces.
57

Let's look at an example code to illustrate extending an interface.


Example

interface ParentInterface{
void parentMethod();
}

interface ChildInterface extends ParentInterface{


void childMethod();
}

class ImplementingClass implements ChildInterface{

public void childMethod() {


System.out.println("Child Interface method!!");
}

public void parentMethod() {


System.out.println("Parent Interface mehtod!");
}
}

public class ExtendingAnInterface {

public static void main(String[] args) {

ImplementingClass obj = new ImplementingClass();

obj.childMethod();
obj.parentMethod();

}
58

Output:

5. inner classes
Java inner class or nested class is a class which is declared inside the class or
interface.

We use inner classes to logically group classes and interfaces in one place so that it can
be more readable and maintainable.

Additionally, it can access all the members of outer class including private data
members and methods.

Syntax

class OuterClass
{
//code
class InnerClass
{
//code
}
}

5.1 uses of inner classes


There are basically three advantages of inner classes in java. They are as follows:

1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.

2) Nested classes are used to develop more readable and maintainable


code because it logically group classes and interfaces in one place only.

3) Code Optimization: It requires less code to write.


59

Difference between nested class and inner class in


Java
Inner class is a part of nested class. Non-static nested classes are known as inner
classes.

Types of Nested classes


There are two types of nested classes non-static and static nested classes.The non-
static nested classes are also known as inner classes.

o Non-static nested class (inner class)

1. Member inner class

2. Anonymous inner class

3. Local inner class


o Static nested class

Type Description

Member Inner A class created within class and outside method.


Class

Anonymous Inner A class created for implementing interface or extending class. Its
Class name is decided by the java compiler.

Local Inner Class A class created within method.

Static Nested A static class created within class.


Class

Nested Interface An interface created within class or interface.

5.2 Types of inner classes


60

o Non-static nested class (inner class)

1. Member inner class

2. Anonymous inner class

3. Local inner class

o Static nested class(static inner class)

1. Member inner class


A non-static class that is created inside a class but outside a method is called member
inner class.

Syntax:

1. class Outer{  
2.  //code  
3.  class Inner{  
4.   //code  
5.  }  
6. }  

Java Member inner class example


In this example, we are creating msg() method in member inner class that is accessing
the private data member of outer class.

1. class TestMemberOuter1{  
2.  private int data=30;  
3.  class Inner{  
4.   void msg(){System.out.println("data is "+data);}  
5.  }  
6.  public static void main(String args[]){  
7.   TestMemberOuter1 obj=new TestMemberOuter1();  
8.   TestMemberOuter1.Inner in=obj.new Inner();  
9.   in.msg();  
10. }  
11.}  
Test it Now
61

Output:

data is 30

2. Local inner class


A class i.e. created inside a method is called local inner class in java. If you want to
invoke the methods of local inner class, you must instantiate this class inside the
method.

Java local inner class example


1. public class localInner1{  
2.  private int data=30;//instance variable  
3.  void display(){  
4.   class Local{  
5.    void msg(){System.out.println(data);}  
6.   }  
7.   Local l=new Local();  
8.   l.msg();  
9.  }  
10. public static void main(String args[]){  
11.  localInner1 obj=new localInner1();  
12.  obj.display();  
13. }  
14.}  
Test it Now

Output:

30

3.Anonymous inner class


A class that have no name is known as anonymous inner class in java. It should be
used if you have to override method of class or interface. Java Anonymous inner class
can be created by two ways:
62

1. Class (may be abstract or concrete).

2. Interface

Java anonymous inner class example using class


1. abstract class Person{  
2.   abstract void eat();  
3. }  
4. class TestAnonymousInner{  
5.  public static void main(String args[]){  
6.   Person p=new Person(){  
7.   void eat(){System.out.println("nice fruits");}  
8.   };  
9.   p.eat();  
10. }  
11.}  
Test it Now

Output:

nice fruits

3. static nested class or static inner class


A static class i.e. created inside a class is called static nested class in java. It cannot
access non-static data members and methods. It can be accessed by outer class name.

o It can access static data members of outer class including private.

o Static nested class cannot access non-static (instance) data member or method.

Java static nested class example with instance


method
1. class TestOuter1{  
2.   static int data=30;  
3.   static class Inner{  
4.    void msg(){System.out.println("data is "+data);}  
5.   }  
6.   public static void main(String args[]){  
63

7.   TestOuter1.Inner obj=new TestOuter1.Inner();  
8.   obj.msg();  
9.   }  
10.}  
Test it Now

Output:

data is 30

In this example, you need to create the instance of static nested class because it has
instance method msg(). But you don't need to create the object of Outer class because
nested class is static and static properties, methods or classes can be accessed without
object.

6. packages
Defination : 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.


64

6.2 creating and accessing a 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. }  
How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename  

For example

1. javac -d . Simple.java  
How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.
65

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package

How to access package from another package?


There are three ways to access the package from outside the package.

1. import package.*;

2. import package.classname;

3. fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.

The import keyword is used to make the classes and interface of another package
accessible to the current package.

Example of package that import the packagename.*


1. //save by A.java  
2. package pack;  
3. public class A{  
4.   public void msg(){System.out.println("Hello");}  
5. }  
1. //save by B.java  
2. package mypack;  
3. import pack.*;  
4.   
5. class B{  
6.   public static void main(String args[]){  
7.    A obj = new A();  
8.    obj.msg();  
66

9.   }  
10.}  
Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.

Example of package by import package.classname


1. //save by A.java  
2.   
3. package pack;  
4. public class A{  
5.   public void msg(){System.out.println("Hello");}  
6. }  
1. //save by B.java  
2. package mypack;  
3. import pack.A;  
4.   
5. class B{  
6.   public static void main(String args[]){  
7.    A obj = new A();  
8.    obj.msg();  
9.   }  
10.}  
Output:Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
67

Example of package by import fully qualified name


1. //save by A.java  
2. package pack;  
3. public class A{  
4.   public void msg(){System.out.println("Hello");}  
5. }  
1. //save by B.java  
2. package mypack;  
3. class B{  
4.   public static void main(String args[]){  
5.    pack.A obj = new pack.A();//using fully qualified name  
6.    obj.msg();  
7.   }  
8. }  
Output:Hello
Note: If you import a package, subpackages will not be imported.

6.3 understanding CLASSPATH

6.4 importing a package

In java, the import keyword used to import built-in and user-defined packages. When

a package has imported, we can refer to all the classes of that package using their

name directly.

The import statement must be after the package statement, and before any other

statement.

Using an import statement, we may import a specific class or all the classes from a

package.

🔔 Using one import statement, we may import only one package or a class.
68

🔔 Using an import statement, we can not import a class directly, but it must be a part

of a package.

🔔 A program may contain any number of import statements.

Importing specific class

Using an importing statement, we can import a specific class. The following syntax is

employed to import a specific class.

Syntax

import packageName.ClassName;

Let's look at an import statement to import a built-in package and Scanner class.

Example

package myPackage;

import java.util.Scanner;

public class ImportingExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

int i = read.nextInt();

System.out.println("You have entered a number " + i);


}
}
69

In the above code, the class ImportingExample belongs to myPackage package, and

it also importing a class called Scanner from java.util package.

Importing all the classes

Using an importing statement, we can import all the classes of a package. To import all

the classes of the package, we use * symbol. The following syntax is employed to

import all the classes of a package.

Syntax

import packageName.*;

Let's look at an import statement to import a built-in package.

Example

package myPackage;

import java.util.*;

public class ImportingExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

int i = read.nextInt();

System.out.println("You have entered a number " + i);

Random rand = new Random();

int num = rand.nextInt(100);


70

System.out.println("Randomly generated number " + num);


}
}

In the above code, the class ImportingExample belongs to myPackage package, and

it also importing all the classes like Scanner, Random, Stack, Vector, ArrayList,

HashSet, etc. from the java.util package.

🔔 The import statement imports only classes of the package, but not sub-packages and

its classes.

🔔 We may also import sub-packages by using a symbol '.' (dot) to separate parent

package and sub-package.

Consider the following import statement.

import java.util.*;

The above import statement util is a sub-package of java package. It imports all the

classes of util package only, but not classes of java package.


71

You might also like