0% found this document useful (0 votes)
7 views

Module 2 Notes New

Uploaded by

Aswin Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Module 2 Notes New

Uploaded by

Aswin Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Inheritance in Java

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.

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

1
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

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.

class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);

2
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Output
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as
of Employee class i.e. code reusability.

Types of inheritance in java


On the basis of class, 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.

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For
Example:

3
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

class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{

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

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...");
}

5
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}

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

class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()

6
{
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.

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");
}

7
}
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?
}
}
Output
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.

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

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.

8
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle
{
//defining a method
void run()
{
System.out.println("Vehicle is running");
}
}
//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

A real example of Java Method Overriding


Consider a scenario where Bank is a class that provides functionality to get the rate of
interest. However, the rate of interest varies according to banks. For example, SBI, ICICI
and AXIS banks could provide 8%, 7%, and 9% rate of interest.

9
Java method overriding is mostly used in Runtime Polymorphism.

//Java Program to demonstrate the real scenario of Java Method Overriding


//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank
{
int getRateOfInterest()
{
return 0;
}
}
//Creating child classes.
class SBI extends Bank
{
int getRateOfInterest()
{
return 8;
}
}

class ICICI extends Bank


{
int getRateOfInterest()
{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
}
}
//Test class to create objects and call the methods
class Test2
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}

10
}

Output
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

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 increase the Method overriding is used to


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

2) Method overloading is performed within class. Method overriding occurs in two


classes that have IS-A
(inheritance) relationship.

3) In case of method overloading, parameter must In case of method


be different. overriding, parameter must be
same.

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


time polymorphism. example of run time
polymorphism.

5) In java, method overloading can't be performed Return type must be same or


by changing return type of the method covariant in method overriding.
only. Return type can be same or different in
method overloading. But you must have to
change the parameter.

11
Java static keyword

The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables , methods, blocks and nested classes . The static keyword belongs to
the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable


If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the class area at the time of class loading.

12
Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable


class Student
{
int rollno;
String name;
String college="ITS";
}

Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and
name, so instance data member is good in such case. Here, "college" refers to the
common property of all objects. If we make it static, this field will get the memory only
once.

Java static property is shared to all objects.

Example of static variable


//Java Program to demonstrate the use of static variable
class Student
{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n)
{
rollno = r;
name = n;
}
//method to display the values
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to show the values of objects
public class TestStaticVariable1
{
public static void main(String args[])
{

13
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}

Output:

111 Karan ITS


222 Aryan ITS

Program of the counter without static variable


In this example, we have created an instance variable named count which is
incremented in the constructor. Since instance variable gets the memory at the time
of object creation, each object will have the copy of the instance variable. If it is
incremented, it won't reflect other objects. So each object will have the value 1 in the
count variable.

14
//Java Program to demonstrate the use of an instance variable
//which get memory each time when we create an object of the class.
class Counter
{
int count=0;//will get memory each time when the instance is created
Counter()
{
count++;//incrementing value
System.out.println(count);
}
public static void main(String args[])
{
//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}

Output:

1
1
1

Program of counter by static variable


As we have mentioned above, static variable will get the memory only once, if any
object changes the value of the static variable, it will retain its value.

//Java Program to illustrate the use of static variable which


//is shared with all objects.
class Counter2
{
static int count=0;//will get memory only once and retain its value
Counter2()
{
count++;//incrementing the value of static variable
System.out.println(count);
}
public static void main(String args[])
{
//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();

15
Counter2 c3=new Counter2();
}
}

Output:

1
2
3

2) Java static method


If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.

Example of static method


//Java Program to demonstrate the use of a static method.
class Student
{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change()
{
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n)
{
rollno = r;
name = n;
}
//method to display values
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to create and display the values of object
public class TestStaticMethod

16
{
public static void main(String args[])
{
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Restrictions for the static method

There are two main restrictions for the static method. They are:

1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.

class A
{
int a=40;//non static
public static void main(String args[])
{
System.out.println(a);
}
}
OUTPUT
Compile Time Error

Q) Why is the Java main method static?


Ans) It is because the object is not required to call a static method. If it were a non-
static method, JVM creates an object first then call main() method that will lead the problem
of extra memory allocation.

17
3) Java static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.

Example of static block


class A2
{
Static
{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}
OUTPUT
static block is invoked
Hello main

this keyword in Java


There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.

Usage of Java this keyword


Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)

18
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

1) this: to refer current class instance variable


The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves the
problem of ambiguity.

class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno;
this.name=name;
this.fee=fee;

19
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}

class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}

Output:

111 ankit 5000.0


112 sumit 6000.0

If local variables(formal arguments) and instance variables are different, there is no


need to use this keyword.

2) this: to invoke current class method


You may invoke the method of the current class by using the this keyword. If you don't
use the this keyword, compiler automatically adds this keyword while invoking the
method. Let's see the example

20
class A
{
void m()
{
System.out.println("hello m");
}
void n()
{
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4
{
public static void main(String args[])
{
A a=new A();
a.n();
}
}

Output:

hello n
hello m

3) this() : to invoke current class constructor


The this() constructor call can be used to invoke the current class constructor. It is used
to reuse the constructor. In other words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:

class A
{
A()
{
System.out.println("hello a");
}
A(int x)
{
this();
System.out.println(x);
}
}

21
class TestThis5
{
public static void main(String args[])
{
A a=new A(10);
}
}

Output:

hello a
10

Real usage of this() constructor call


The this() constructor call should be used to reuse the constructor from the
constructor. It maintains the chain between the constructors i.e. it is used for
constructor chaining.

class Student
{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course)
{
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee)
{
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+course+" "+fee);
}
}
class TestThis7
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();

22
s2.display();
}
}

Output:

111 ankit java 0.0


112 sumit java 6000.0

4) this: to pass as an argument in the method


The this keyword can also be passed as an argument in the method. It is mainly used
in the event handling. Let's see the example:

class S2
{
void m(S2 obj)
{
System.out.println("method is invoked");
}
void p()
{
m(this);
}
public static void main(String args[])
{
S2 s1 = new S2();
s1.p();
}
}

Output:

method is invoked

Application of this that can be passed as an argument:

In event handling (or) in a situation where we have to provide reference of a class to


another one. It is used to reuse one object in many methods.

5) this: to pass as argument in the constructor call


We can pass the this keyword in the constructor also. It is useful if we have to use one
object in multiple classes. Let's see the example:

23
class B
{
A4 obj;
B(A4 obj)
{
this.obj=obj;
}
void display()
{
System.out.println(obj.data);//using data member of A4 class
}
}

class A4
{
int data=10;
A4()
{
B b=new B(this);
b.display();
}
public static void main(String args[])
{
A4 a=new A4();
}
}
Output:10

6) this keyword can be used to return current class instance


We can return this keyword as an statement from the method. In such case, return type
of the method must be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement

return_type method_name()
{
return this;
}

24
Example of this keyword that you return as a statement from
the method
class A
{
A getA()
{
return this;
}
void msg()
{
System.out.println("Hello java");
}
}
class Test1
{
public static void main(String args[])
{
new A().getA().msg();
}
}

Output:

Hello java

25
Super Keyword in Java
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.

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

class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}

Output:tay

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.

27
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}

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.

28
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:

class Animal
{
Animal()
{
System.out.println("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}
}

Output:

animal is created
dog is created

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

class Animal
{
Animal()
{
System.out.println("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
System.out.println("dog is created");
}
}
class TestSuper4
{
public static void main(String args[])
{
Dog d=new Dog();
}
}

Output:

animal is created
dog is created

30
super example: real use
Let's see the real use of super keyword. Here, Emp class inherits Person class so all the
properties of Person will be inherited to Emp by default. To initialize all the property,
we are using parent class constructor from child class. In such way, we are reusing the
parent class constructor.

class Person
{
int id;
String name;
Person(int id,String name)
{
this.id=id;
this.name=name;
}
}
class Emp extends Person
{
float salary;
Emp(int id,String name,float salary)
{
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display()
{
System.out.println(id+" "+name+" "+salary);
}
}
class TestSuper5
{
public static void main(String[] args)
{
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}
}

Output:

1 ankit 45000

31
Final Keyword In Java
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).

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.

class Bike9
{
final int speedlimit=90;//final variable

32
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output:Compile Time Error

2) Java final method


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

Example of final method


class Bike
{
final void run()
{
System.out.println("running");
}
}

class Honda extends Bike


{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
}
}

Output:Compile Time Error

33
3) Java final class
If you make any class as final, you cannot extend it.

Example of final class


final class Bike
{
}

class Honda1 extends Bike


{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda1 honda= new Honda1();
honda.run();
}
}

Output:Compile Time Error

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

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
and non-abstract methods. It needs to be extended and its method implemented. It
cannot be instantiated.

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.

35
Example of abstract class

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

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

36
Example of Abstract class that has an abstract method
In this example, Bike is an abstract class that contains only one abstract method run.
Its implementation is provided by the Honda class.

abstract class Bike


{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}

Output

running safely

Understanding the real scenario of Abstract class


In this example, Shape is the abstract class, and its implementation is provided by the
Rectangle and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the end
user), and an object of the implementation class is provided by the factory method.

A factory method is a method that returns the instance of the class.

In this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.

37
abstract class Shape
{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{
System.out.println("drawing circle");
}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1
{
public static void main(String args[])
{
//In a real scenario, object is provided through method, e.g., getShape() method
Shape s=new Circle1();
s.draw();
}
}

Output

drawing circle

38
Another example of Abstract class in java
abstract class Bank
{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class PNB extends Bank
{
int getRateOfInterest()
{
return 8;
}
}

class TestBank
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}

}
Output

Rate of Interest is: 7 %


Rate of Interest is: 8 %

39
Abstract class having constructor, data member and
methods
An abstract class can have a data member, abstract method, method body (non-
abstract method), constructor, and even main() method.

//Example of an abstract class that has abstract and non-abstract methods


abstract class Bike
{
Bike()
{
System.out.println("bike is created");
}
abstract void run();
void changeGear()
{
System.out.println("gear changed");
}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike
{
void run()
{
System.out.println("running safely..");
}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2
{
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}

40
Output
bike is created
running safely..
gear changed

Rule: If there is an abstract method in a class, that class must be abstract.

class Bike12
{
abstract void run();
}

compile time error

Rule: If you are extending an abstract class that has an abstract method, you must either
provide the implementation of the method or make this class abstract.

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java

In other words, you can say that interfaces can have abstract methods and variables.
It cannot have a method body.

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.

41
How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.

Syntax:

interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}

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.

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

Java Interface Example


In this example, the Printable interface has only one method, and its implementation
is provided in the A6 class.

interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}

43
public static void main(String args[])
{
A6 obj = new A6();
obj.print();
}
}
Output
Hello

Java Interface Example: Drawable


In this example, the Drawable interface has only one method. Its implementation is
provided by Rectangle and Circle classes. In a real scenario, an interface is defined by
someone else, but its implementation is provided by different implementation
providers. Moreover, it is used by someone else. The implementation part is hidden by
the user who uses the interface.

//Interface declaration: by first user


interface Drawable
{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println("drawing circle");
}
}
//Using interface: by third user
class TestInterface1
{
public static void main(String args[])
{

44
Drawable d=new Circle();//In real scenario, object is provided by metho
d e.g. / getDrawable()
d.draw();
}
}

Output:

drawing circle

Java Interface Example: Bank


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

interface Bank
{
float rateOfInterest();
}
class SBI implements Bank
{
public float rateOfInterest()
{
return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{
return 9.7f;
}
}
class TestInterface2
{
public static void main(String[] args)
{
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}

45
}

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.

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[])

46
{
A7 obj = new A7();
obj.print();
obj.show();
}
}

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:

interface Printable
{
void print();
}
interface Showable
{
void print();
}

class TestInterface3 implements Printable, Showable


{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
TestInterface3 obj = new TestInterface3();
obj.print();
}
}

Output:

Hello

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

interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class TestInterface4 implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

public static void main(String args[])


{
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}

Output:

Hello
Welcome

48
Q) What is marker or tagged interface?
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.

//How Serializable interface is written?


public interface Serializable
{
}

Difference between abstract class and interface


Abstract class and interface both are used to achieve abstraction where we can declare
the abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given
below.

Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods.
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 variables.
final, static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.

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


declare abstract class. interface.

49
6) An abstract class can extend another An interface can extend another Java interface
Java class and implement multiple Java only.
interfaces.

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


using keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

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

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface


achieves fully abstraction (100%).

Example of abstract class and interface in Java


Let's see a simple example where we are using interface and abstract class both.

//Creating interface that has 4 methods


interface A
{
void a();//by default, public and abstract
void b();
void c();
void d();
}

//Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A
{
public void c()
{
System.out.println("I am C");
}
}

//Creating subclass of abstract class, now we need to provide the implementation of rest of t
he methods

50
class M extends B
{
public void a()
{
System.out.println("I am a");
}
public void b()
{
System.out.println("I am b");
}
public void d()
{
System.out.println("I am d");
}
}

//Creating a test class that calls the methods of A interface


class Test5
{
public static void main(String args[])
{
A a=new M();
a.a();
a.b();
a.c();
a.d();
}
}

Output:

I am a
I am b
I am c
I am d

51
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in
different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So polymorphism means many
forms.

There are two types of polymorphism in Java: compile-time polymorphism and


runtime polymorphism. We can perform polymorphism in java by method overloading
and method overriding.

If you overload a static method in Java, it is the example of compile time


polymorphism. Here, we will focus on runtime polymorphism in java.

Runtime Polymorphism in Java


Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to
an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a


superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known
as upcasting. For example:

52
class A
{
}
class B extends A
{
}
A a=new B();//upcasting

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

interface I
{
}
class A
{
}
class B extends A implements I
{
}

Example of Java Runtime Polymorphism


In this example, we are creating two classes Bike and Splendor. Splendor class extends
Bike class and overrides its run() method. We are calling the run method by the
reference variable of Parent class. Since it refers to the subclass object and subclass
method overrides the Parent class method, the subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.

class Bike
{
void run()
{
System.out.println("running");
}
}
class Splendor extends Bike
{

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

Java Runtime Polymorphism Example: Bank


Consider a scenario where Bank is a class that provides a method to get the rate of
interest. However, the rate of interest may differ according to banks. For example, SBI,
ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7% rate of interest.

Note: This example is also given in method overriding but there was no upcasting.

class Bank
{
float getRateOfInterest()
{
return 0;
}
}
class SBI extends Bank
{

54
float getRateOfInterest()
{
return 8.4f;
}
}
class ICICI extends Bank
{
float getRateOfInterest()
{
return 7.3f;
}
}
class AXIS extends Bank
{
float getRateOfInterest()
{
return 9.7f;
}
}
class TestPolymorphism
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}

Output:

SBI Rate of Interest: 8.4


ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

55
Java Runtime Polymorphism with Multilevel
Inheritance
Let's see the simple example of Runtime Polymorphism with multilevel inheritance.

class Animal
{
void eat()
{
System.out.println("eating");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating fruits");
}
}
class BabyDog extends Dog
{
void eat()
{
System.out.println("drinking milk");
}
public static void main(String args[])
{
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}

Output:

eating
eating fruits
drinking Milk

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

int data=30;

57
Here data variable is a type of int.

2) References have a type


class Dog
{
public static void main(String args[])
{
Dog d1;//Here d1 is a type of Dog
}
}

3) Objects have a type


An object is an instance of particular java class, but it is also an instance of its superclass.

class Animal
{
}

class Dog extends Animal


{
public static void main(String args[])
{
Dog d1=new Dog();
}
}
Here d1 is an instance of Dog class, but it is also an instance of Animal.

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...");
}

58
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();
}
}

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.

59
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined
package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.

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.

60
Simple example of java package
The 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");
}
}
How to compile java package?

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

javac -d directory javafilename

For example

javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc.
If you want to keep the package within the same directory, you can use . (dot).

How to run java package program?

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

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . rep
folder.

61
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 sub packages.

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

//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello

62
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

//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}

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.

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

Example of package by import fully qualified name


//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import
the subpackage as well.

64
Note: Sequence of the program must be package then import then class.

How to send the class file to another directory or


drive?
There is a scenario, I want to put the class file of A.java source file in classes folder of
c: drive. For example:

65
//save as Simple.java

package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

To Compile:

e:\sources> javac -d c:\classes Simple.java

To Run:

To run this program from e:\source directory, you need to set classpath of the directory where
the class file resides.

e:\sources> set classpath=c:\classes;.;

e:\sources> java mypack.Simple

Another way to run this program by -classpath switch of java:


The -classpath switch can be used with javac and java tool.

To run this program from e:\source directory, you can use -classpath switch of java
that tells where to look for class file. For example:

e:\sources> java -classpath c:\classes mypack.Simple

Output:Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.

o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent

66
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file in
the jre/lib/ext folder.

Access Modifiers in Java


There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native,
volatile, transient, etc. Here, we are going to learn the access modifiers only.

67
Understanding Java Access Modifiers
Let's understand the access modifiers in Java by a simple table.

1) Private
The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private
data member and private method. We are accessing these private members from
outside the class, so there is a compile-time error.

class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}

68
}

2) Default
If you don't use any modifier, it is treated as default by default. The default modifier
is accessible only within package. It cannot be accessed from outside the package. It
provides more accessibility than private. But, it is more restrictive than protected, and
public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing
the A class from outside its package, since A class is not public, so it cannot be accessed
from outside the package.

//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above example, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.

3) Protected
The protected access modifier is accessible within package and outside the package
but through inheritance only.

69
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg method
of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.

//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.*;

class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output:Hello

4) Public
The public access modifier is accessible everywhere. It has the widest scope among
all other modifiers.

Example of public access modifier

//save by A.java

70
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

//save by B.java

package mypack;
import pack.*;

class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello

71

You might also like