0% found this document useful (0 votes)
33 views57 pages

Unit 2

The document discusses inheritance in Java including types of inheritance like single, multilevel and hierarchical inheritance. It also covers method overriding, the super keyword, preventing inheritance using the final keyword and polymorphism in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views57 pages

Unit 2

The document discusses inheritance in Java including types of inheritance like single, multilevel and hierarchical inheritance. It also covers method overriding, the super keyword, preventing inheritance using the final keyword and polymorphism in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 57

UNIT II

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 1.For Method Overriding
---→(so runtime polymorphism can be achieved).

2. For Code Reusability.

Terms used in Inheritance

Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.

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.

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.
class Subclass-name extends Superclass-name
{
//methods and fields
}
Note: 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
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);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
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.
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.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical
inheritance. class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
super key word
The super keyword in Java is a reference variable which is used to refer
immediate parent class object.

Usage of Java super Keyword

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

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

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


class Animal { class Dog extends Animal {
public void move() { public void move() {
System.out.println("Animals super.move(); // invokes the super class
can move"); method
} System.out.println("Dogs can walk and run");
public void eat() super.eat();
{ }
}
System.out.println(" Animals
public class TestDog {
Will eat."); public static void main(String args[]) {
} Dog d=new Dog();
} d.move();
Animal obj = new Dog(); // Animal reference
but Dog object
obj.move(); // runs the method in Dog class
}
}
Preventing inheritance

While one of Java's strengths is the concept of inheritance, in which one class
can derive from another, sometimes it's desirable to prevent inheritance by
another class. To prevent inheritance, use the keyword "final" when creating
the class.

Why Prevent Inheritance?

The main reason to prevent inheritance is to make sure the way a class behaves
is not corrupted by a subclass.
Suppose we have a class Account and a subclass that extends it,
OverdraftAccount. Class Account has a method getBalance()

public final class Account


{
statements
}

This means that the Account class cannot be a superclass, and the OverdraftAccount class can
no longer be its subclass.

Sometimes, you may wish to limit only certain behaviors of a superclass to avoid corruption
by a subclass. For example, OverdraftAccount still could be a subclass of Account, but it should
be prevented from overriding the getBalance() method.
public class Account {
private double balance;
public final double getBalance()
{
return this.balance;
}
}

final is a non-access modifier for Java elements. The final modifier is used for
finalizing the implementations of classes, methods, and variables.
What are ways to Prevent Inheritance in Java Programming?
There are 2 ways to stop or prevent inheritance in Java programming.
By using final keyword with a class orBy using a private constructor in a class.

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.

Java final variable


If you make any variable as final, you cannot change the value of final variable(It
will be constant)
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
63.151/Bike9.java:4: error: cannot assign a value to final variable
speedlimit
speedlimit=400;
^
1 error
Java final method
If you make any method as final, you cannot override it.
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();
}
}
Compile by: javac Honda.java
63.151/Honda.java:6: error: run() in Honda cannot override run() in Bike with 100kmph");}
^
overridden method is final
1 error
Java final class
If you make any class as final, you cannot extend it.

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();
}
}
Compile by: javac Honda1.java
3.133/Honda1.java:3: error: cannot inherit from final Bike class Honda1
extends Bike{}
Polymorphism
Polymorphism is briefly described as “one interface, many
implementations”.
Polymorphism in Java is a concept by which we can perform a single action
in different ways.

1. Compile time polymorphism


2. Run time polymorphism

Compile time polymorphism is method overloading whereas Runtime time


polymorphism is done using inheritance and interface.
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it
is known as method overriding in Java.

Rules for Java Method Overriding


1.The method must have the same name as in the parent class
2.The method must have the same parameter as in the parent class.
3.There must be an IS-A relationship (inheritance).
class Vehicle
{
void run(){
System.out.println("Vehicle is running");
}
}
class Bike2 extends Vehicle{
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
} } OUT PUT:
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 at
compile-time. In this process, an overridden method is called through the
reference variable of a superclass.
class Car {
void run()
{ System.out.println(“car is running”); }
}
class Audi extends Car {
Since method invocation is void run()
determined by the JVM not { System.out.prinltn(“Audi is running safely with
compiler, it is known as 100km”); }
runtime polymorphism. public static void main(String args[])
{
Car b= new Audi(); //upcasting
b.run();
} }
class Bank{
float getRateOfInterest(){return 0;} class TestPolymorphism{
} public static void main(String args[]){
class SBI extends Bank{ Bank b;
float getRateOfInterest(){return 8.4f;} b=new SBI();
} System.out.println("SBI Rate of Interest:
class ICICI extends Bank{ "+b.getRateOfInterest());
float getRateOfInterest(){return 7.3f;} b=new ICICI();
} System.out.println("ICICI Rate of Interest:
class AXIS extends Bank{ "+b.getRateOfInterest());
float getRateOfInterest(){return 9.7f;} b=new AXIS();
} System.out.println("AXIS Rate of Interest:
"+b.getRateOfInterest());
}
}
Java Abstract Class and Abstract Methods
A class which is declared with the abstract keyword is known as an abstract
class in Java. It can have abstract (method with out body) 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.

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 1.abstract class A{}

•An abstract class must be declared with an abstract keyword.


•It can have abstract and non-abstract methods.
•It cannot be instantiated.
•It can have constructors and static methods also.
•It can have final methods which will force the subclass not to change
the body of the method.
Abstract Method in Java

A method which is declared as abstract and does not have implementation is


known as an abstract method.

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


abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
} OUT PUT : running safely
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[]){
Shape s=new Circle1
s.draw();
}
} output: drawing circle
Abstract class having constructor, data member and
methods
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear(); bike is created
} running safely..
} gear changed
Interface
An interface in Java is a blueprint of a class. It has static constants and
abstract methods.

An interface in Java is similar to class. It is a collection of 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.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.


A class implements an interface, thereby inheriting the abstract methods of the interface.

Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.

Why use Java interface?

1) It is used to achieve abstraction.

2) By interface, we can support the functionality of multiple inheritance.


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.

interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
The relationship between classes and interfaces
A class extends another class, an interface extends another interface, but
a class implements an interface.
interface inter
{
int a=10,b=20;
public void add();
}
class c1 implements inter
{
public void add()
{
int sum=a+b;
System.out.println("Sum of numbers is:" +sum);
}
public static void main(String[] srgs)
{
c1 obj= new c1();
obj.add();
}
} output: Sum of numbers is: 30
interface Drawable{
void draw();
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
Drawable d1=new Rectangle();
d1.draw();
}} output: drawing circle
drawing rectangle
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 inter public void sub()
{ {
int a=10,b=20; int r=c-d;
public abstract void add(); System.out.println(" Difference of numbers
} is :" +r);
interface inter1 }
{ public static void main(String[] args)
int c=20,d=10; {
public abstract void sub(); c1 obj=new c1();
} obj.add();
class c1 implements inter,inter1 obj.sub();
{ }
public void add() } Output: Sum of numbers is : 30
{ Difference of numbers is: 10
int sum=a+b;
System.out.println(" Sum of numbers
is :" +sum);
}
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();
} Out put : Hello
}
Java Nested Interface
An interface, i.e., declared within another interface or class, is known as a
nested interface. The nested interfaces are used to group related interfaces
so that they can be easy to maintain.

Points to remember

•The nested interface must be public if it is declared inside the interface,


but it can have any access modifier if declared within the class.

•Nested interfaces are declared static


Syntax of nested interface which is declared within the
interface
interface interface_name{
...
interface nested_interface_name{

...
}
} Syntax of nested interface which is declared within the
class
class class_name{
...
interface nested_interface_name{
...
}
}
Example of nested interface which is declared within the interface
interface Showable
{ public static void main(String args[])
void show(); {
interface Message c1 obj1=new c1();
{ obj1.msg();
void msg(); obj1.show();
} }
} }
class c1 implements Showable.Message
{ Output: Hello nested interface
public void msg() Welcome to nested interface
{
System.out.println("Hello nested interface");

public void show()


{
System.out.println("Welcome to nested interface");
}
Example of nested interface which is declared within the class
class A public static void main(String args[]){
{
interface Message inter obj1=new inter();
{ obj1.show();
void msg(); obj1.msg();
void show(); }
} }
}
Output: Welcome to nested interface
class inter implements A.Message Hello nested interface
{
public void msg()
{
System.out.println("Hello nested interface");

}
public void show()
{
System.out.println(" Welcome to nested interface");
}
Java Default Methods
Java provides a facility to create default methods inside the interface. Methods
which are defined inside the interface and tagged with default are known as
default methods. These methods are non-abstract methods.
interface add class c1 implements add{
{ public void addition()
public void addition(); {
default void addition1() int i=1,j=4,k;
{ int a=1,b=2,c; k=i+j;
c=a+b; System.out.println(k); }
System.out.println(c); public static void main(String[] args)
} { add obj=new c1();
static void sub() obj.addition();
{ obj.addition1();
int l=20,m=10,n; add.sub();
n=l-m; }
System.out.println(n); } output:5
} 3
} 10
Difference between abstract class and interface
Abstract class Interface
1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. Since Java 8, it can have default
and static methods also.

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

3) Abstract class can have final, non-final, static and non-static Interface has only static and final variables.
variables.
4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class.

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

6) An abstract class can extend another Java class and implement An interface can extend another Java interface only.
multiple Java interfaces.
7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword "implements".

8) A Java abstract class can have class members like private, Members of a Java interface are public by default.
protected, etc.
9)Example:public abstract clasShape{ Example:
public abstract void draw(); public interface Drawable{
} void draw();
}
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.
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");
}
}
1. Core Packages: Core Packages are predefined
packages given by Sun MicroSystems which begin with
“java”.
2. Extended Packages: Extended packages are also
predefined packages given by Sun Microsystems which
begin with “javax”.
3. Third-Party Packages: Third-Party Packages are also
predefined packages that are given by some other
companies as a part of Java Software.
Example:oracle.jdbc, com.mysql, etc
User-Defined Packages in Java
In Java, we can also create user-defined packages according to our
requirements. To create the user-defined packages we have to use a java
keyword called “package.
Rules:
1. While writing the package name we can specify packages in any number of
levels but specifying one level is mandatory.
2. The package statement must be written as the first executable statement in
the program.
3. We can write at most one package statement in the program

package Demo;
public class PackageDemo {
public static void main(String args[]) {
System.out.println("Have a Nice
Day...!!!");
}
}
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.
//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();
}
}
2) Using packagename.classname
If you import package.classname then only declared class of this package will
be accessible.
//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();
}
}
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.

//save by A.java
package pack; //save by B.java
public class A{ package mypack;
public void msg(){System.out.println("Hello");} class B{
} public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
C:\Users\MRUH\Desktop\javaex\package>javac -d . B.java

C:\Users\MRUH\Desktop\javaex\package>java pack.Simple
Subpackage in java
Package inside the package is called the subpackage. It should be created to
categorize the package further.

package pack.package;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}

You might also like