Java Programming
Unit-2
Inheritance, Interface and
Packages
Contents-
• Inheritance
• Interface
• Packages
• Inheritance:
• Definition,
• Super classes, and Subclasses,
• Types of Inheritance
• Overriding and Hiding Methods,
• Polymorphism,
• Super keyword,
• Final Classes and Methods,
• Abstract Classes and Methods 2
Contents-
• Interfaces:
• Defining an Interface,
• Implementing an Interface,
• Using an Interface as a Type,
• Packages:
• Class importing,
• Creating a Package,
• Naming a Package,
• Using Package Members,
• Managing Source and Class Files.
3
Inheritance
• When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance.
• It is the mechanism in java by which one class is allowed to inherit the
features(variables and methods) of another class.
• Super Class:
• The class whose features are inherited is known as superclass.
• Also known as a base class or a parent class.
• Sub Class:
• The class that inherits the features of other class is known as a subclass.
• Also known as a derived class, extended class, or child class.
• The subclass can add its own fields and methods in addition to the superclass fields
and methods.
• It provides code reusability.
4
Inheritance
• The idea behind inheritance in Java is-
• We can create new classes that are built upon existing classes.
• When we inherit from an existing class, we can reuse methods and fields of the
parent class.
• We 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
• For Method Overriding (Runtime Polymorphism)
• For Code Reusability.
• If the code of the superclass is changed, the subclasses are also affected.
So, the parent class and child class are dependent on each other.
5
Terms used in Inheritance
• Class: A class is a group of objects which have common properties.
• 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:
• Reusability is a mechanism which facilitates to reuse the fields and
methods of the existing class when we create a new class. 6
Inheritance syntax
class Superclass-name
{ //Superclass body
}
class Subclass-name extends Superclass-name
{ //methods and fields
}
• The extends keyword indicates that
• Making a new class that derives from an existing class.
• The meaning of "extends" is to increase the functionality.
7
Inheritance Example
• 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.
8
Inheritance Example
9
Inheritance Example
10
Inheritance Example
11
Inheritance Types
• On the basis of class, there are five types of inheritance in java:
• Single inheritance
• Multilevel inheritance
• Hierarchical inheritance
• Multiple inheritance
• Hybrid inheritance
• In java programming,
• Multiple inheritance and Hybrid inheritance is supported through
interface only.
12
Single Inheritance
• When one class inherits another class, it is known
as a single inheritance.
• It has one super class and one subclass.
• The below flow diagram shows that class B
extends only one class which is A.
• Example- A is a parent class of B and B would
be a child class of A.
13
Single Inheritance Example
14
Single Inheritance Example
15
Multilevel Inheritance
• When there is a chain of inheritance, it is known as
multilevel inheritance.
• It has grand parent class, parent class and child class.
• One can inherit from a derived class, thereby making this
derived class the base class for the new class.
• One class inherits properties from a second class which
again has inherits properties from another class.
• In flow diagram, C is subclass or child class of B and B is a
child class of A.
16
17
18
Hierarchical Inheritance
• When two or more classes inherits a single
class, it is known as hierarchical inheritance.
• In this inheritance one class is inherited by
many sub classes.
• It has one super class and many subclasses.
• Example- class B, C and D inherits the same
class A.
• A is parent class (or base class) of B, C & D.
19
Hierarchical Inheritance Example
class Superclass
{ class Example
void method1() { {
[Link]("This is Super class"); public static void main(String args[])
} {
} Subclass2 obj=new Subclass2();
obj.method1();
class Subclass1 extends Superclass obj.method3();
{ obj.method2(); //C. T. Error
void method2() { }
[Link]("This is Subclass one"); }
}
}
class Subclass2 extends Superclass
{
void method3() {
[Link]("This is Subclass two");
}
} 20
Multiple Inheritance
• If one subclass inherits features from more than one super classes, then
it is called as Multiple inheritances.
• In this, one class inherits from more than one base class.
• The problem with “multiple inheritance” is that the derived class will
have to manage the dependency on two base classes.
• To reduce the complexity and simplify
the language, multiple inheritance
is not supported in java.
• In Java, Multiple inheritance is supported
through interface only.
21
Why multiple inheritance is not supported in java?
22
Hybrid Inheritance
• Hybrid inheritance is a combination of
Single and Multiple inheritance.
• To reduce the complexity and simplify
the language, Hybrid inheritance
is not supported in java.
• In Java, Hybrid inheritance is
supported through interface only.
23
Polymorphism
•The word "poly" means many and "morphs" means forms.
•Polymorphism means "many forms” and it occurs when we have many
classes that are related to each other by inheritance.
•If one task is performed in different ways, it is known as polymorphism.
•It is a mechanism where object behaves differently in different situations.
•Inheritance lets us inherit attributes and methods from another class.
•Polymorphism uses those methods to perform different tasks.
•Polymorphism allows us to perform a single action in different ways.
24
Polymorphism
• In Java polymorphism is mainly divided into two types:
• Compile-time Polymorphism
• Runtime Polymorphism
• In Java,
• Method overloading for Compile-time Polymorphism
• Method overriding for Runtime Polymorphism
are used to achieve polymorphism.
25
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.
• 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.
• If super class and sub class both have same method. Then it is method
overriding.
• In method overriding, always child methods will be invoked.
• Method in sub class is overriding/hiding method
• Method in super class is overridden/hidden method. 26
without method overriding
27
with method overriding
28
Method overriding
• Usage of Method Overriding
• Method overriding is used to provide the specific implementation of
a method which is already provided by its superclass.
• Method overriding is used for runtime polymorphism
• Rules for Method Overriding
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).
29
Method overriding Example
30
Method overriding Example
31
Super Keyword
• The super keyword in Java is a reference variable.
• It is used to refer immediate parent class object.
• Super keyword is used to access a member of the superclass that
has been hidden by a member of a subclass.
• Usage of Java super Keyword
• super can be used
• To refer parent class instance variable.
• To invoke parent class method.
• super() can be used to invoke parent class constructor.
32
To refer parent class instance variable
• To access the data members or fields of parent class when parent
& child class have member with same name.
• A variable in child class which is already present in the parent
class.
• To access the variable of parent class, use the super keyword.
• To access a member of the superclass that has been hidden by a
member of a subclass.
• Form of super keyword-
[Link]
33
To refer parent class instance variable
class Superclass {
int num = 100;
}
class Subclass extends Superclass {
//The same variable num is declared in the Subclass which is
already present in the Superclass
int num = 110;
void print() {
[Link](num);
}
public static void main(String args[]){
Subclass obj= new Subclass();
[Link]();
} }
To refer parent class instance variable
class Superclass {
int num = 100;
}
class Subclass extends Superclass {
int num = 110;
void print()
{
[Link]([Link]);
}
public static void main(String args[]) {
Subclass obj= new Subclass();
[Link]();
}
}
36
To invoke parent class method
• When a child class declares a same method which is already present
in the parent class then this is called method overriding.
• The super keyword is used to invoke parent class method.
• It should be used if subclass contains the same method as parent
class.
• It is used if method is overridden.
• Syntax🡪 [Link]
• Method overriding terminologies:
-Overridden method: The method of parent class
-Overriding method: The method of child class 37
To invoke parent class method
38
39
To invoke parent class constructor
• When we create the object of sub class-
-new keyword invokes the constructor of child class.
-It implicitly invokes the constructor of parent class.
• Use super() as the first statement in the constructor of child class.
• Order to execution-
• when we create the object of child class is:
-parent class constructor is executed first
-then the child class constructor is executed.
40
To invoke parent class constructor
• Forms of super keyword
super() 🡪 call no-arg constructor
super(parameter-list) 🡪 call parameterized constructor
• Compiler itself adds super() as the first statement in the
constructor of child class.
• To invoke the no-arg constructor of parent class.
• Explicitly use super(parameter-ist) to invoke parameterized
constructor of parent class.
41
To invoke parent class constructor
42
43
Output
• Constructor of parent class
• Constructor of child class
• Hello!
• Constructor of parent class
• arg constructor of child class
• Hello!
44
To invoke parent class constructor
• Default constructor is provided by compiler automatically if there is
no constructor.
• It also adds super() as the first statement.
• super() is added in each class constructor automatically by
compiler if there is no super() or this().
45
To invoke parent class constructor
46
47
Use of final keyword
• The final keyword in java is used to restrict the user.
• The java final keyword can be used in many context.
• Final can be:
• variable
• method
• class
• final keyword is used to-
-Prevent variable value change
-Prevent method Overriding
-Prevent Inheritance
48
final variable
• If we make any variable as final, we cannot change the value of
final variable
• It will be constant.
• Final keyword id used to stop value change.
• Syntax- final int speed;
final int spedd=100;
• Value can't be changed because final variable once assigned a
value can never be changed.
49
final variable example
class Bike class Bike
{ {
final int speed=90; //final variable final int speed=90; //final variable
void run() void run()
{ {
speed=400; SOP(“Speed is:”+speed);
SOP(“Speed is:”+speed); }
}
public static void main(String args[])
public static void main(String args[]) {
{ Bike ob=new Bike();
Bike ob=new Bike(); [Link]();
[Link](); }
} }
} 50
final method
• If we make any method as final, we cannot override it.
• Final keyword is used to stop method overriding.
Use of final to prevent method Overriding:
• Use final to disallow a method from being overridden.
• Specify final as a modifier at the start of method declaration.
• Methods declared as final cannot be overridden.
• Syntax:
final void display()
51
final method to stop method overriding
class A {
final void display()
{
[Link]("This is a final method.");
}
}
class B extends A {
void display() // ERROR! Can't override.
{
[Link](“Invalid");
}
public static void main(String args[])
{
B ob= new B();
[Link]();
}
} 52
final method can be inherited
•final method is inherited but you cannot override it.
class A {
final void display()
{
[Link]("This is a final method.");
}
}
class B extends A
{
public static void main(String args[])
{
B ob= new B();
[Link]();
}
} 53
final class
• If we make any class as final, we cannot extend it.
• Final keyword is used to stop inheritance.
• Using final to Prevent Inheritance
• Use final to prevent a class from being inherited.
• To do this, precede the class declaration with final.
• Declaring a class as final implicitly declares all of its members
as final.
• Syntax: final class A
//…
class B extends class A // ERROR! Can't subclass A
//… 54
final class example
final class A {
void display()
{
[Link]("This is a final method.");
}
}
class B extends A { // ERROR! Can't extends.
void display()
{
[Link](“Invalid");
}
public static void main(String args[])
{
B ob= new B();
[Link]();
}
55
}
Interface
• Contents
• Defining an Interface
• Implementing an Interface
• Using an Interface as a Type
56
Abstract Class
• A class that is declared using “abstract” keyword is known as
abstract class.
• If a class contain any abstract method then the class is declared
as abstract class.
• An abstract class cannot be instantiated.
• We are not allowed to create an object of it.
• It can have abstract methods as well as concrete methods.
• Abstract classes can have Constructors, Member variables and
Normal methods.
Abstract Class
• An abstract classes are incomplete, they have abstract methods
that have no body.
• An abstract class has no use until & unless it is extended by
some other class.
• It is used to provide partial abstraction.
• The class which is extending abstract class must override all the
abstract methods.
• When you extend Abstract class with abstract method, you must
define the abstract method in the child class.
Abstract method
• A method without body is known as abstract method.
• It has no implementation details.
• The method body will be defined by its subclass.
• Abstract method can never be final and static.
• A method must always be declared in an abstract class.
• If a class has an abstract method, it should be declared abstract
as well.
Abstract method
• Any class that extends an abstract class must implement all
the abstract methods declared by the super class.
• Syntax:-
abstract type name(parameter-list);
e.g. abstract int method1(int n1, int n2);
• When Abstract methods are used?
• When two or more subclasses are expected to do a similar
thing in different ways through different implementations.
Example of Abstract class
abstract class A{
abstract void show();
}
class B extends A{
void show(){
[Link]("this is DYPGROUP.");
}
public static void main(String[] args) {
B b = new B();
[Link]();
}
}
Interface in java
• Abstract class is used to provide partial abstraction.
• An interface is used for full abstraction.
• Abstraction is a process where we show only “relevant” data and
“hide” unnecessary details of an object from the user.
• Interface are syntactically similar to classes but it is not a class.
• An interface can have methods and variables just like the class.
Interface
• Methods declared in interface are by default public abstract
(declared without any body).
• The variables declared in an interface are public, static &
final by default.
• They cannot be changed by the implementing class.
• Interfaces are declared by specifying a keyword “interface”.
• When we create an interface it defines what a class can do
without saying anything about how the class will do it.
Interface Syntax
• Syntax:
interface interface-name {
variable –name;
Method();
}
• Example:
interface result {
int a; /* All the variables are public static final by default*/
int b;
void method1(); /* All the methods are public abstract by default */
void method2();
}
Interface Implementation
• We cannot create the object of an interface.
• Class implements interfaces.
• Interface cannot implement a class.
• Class uses keyword implements to implement interface.
• One interface can be implemented by one or more classes.
• One class can implement one or more interfaces.
• Interface can extend one or more other interface.
Example of Interface
interface Moveable
{
int AVERAGE-SPEED=40;
void move();
}
• What compiler sees?
Interface Implementation
Compiler automatically converts-
-methods of Interface as public and abstract, and
-data members as public, static and final by default.
Internal addition by the compiler
• The Java compiler adds
• public and abstract keywords before the interface method.
• public, static and final keywords before data members.
Relationship between classes & interfaces
• A class extends another class.
• An interface extends another interface.
• But a class implements an interface.
Why use Java interface?
• There are mainly three reasons to use interface.
• It is used to achieve full abstraction.
• Interface supports the functionality of multiple inheritance.
Interface Example
interface Moveable{
int AVG-SPEED = 40;
void move();
}
class Vehicle implements Moveable{
public void move() {
[Link]("Average speed is"+AVG-SPEED");
}
public static void main (String[] arg) {
Vehicle vc = new Vehicle();
[Link]();
}
}
Interface extends other Interface
• Classes implements interfaces, but an interface extends other
interface.
• Example:-
interface marks{
get();
}
interface result extends marks{
show();
}
Interface extends other Interface
interface A { public void meth3() {
void meth1();
[Link]("Implement
void meth2(); meth3()");
}
// B now includes meth1() and meth2() -- it adds }
meth3().
}
interface B extends A {
void meth3(); class Execute {
} public static void main(String arg[]) {
MyClass ob = new MyClass();
class MyClass implements B {
public void meth1() { ob.meth1();
[Link]("Implement meth1()"); ob.meth3();
} }}
Interface example without creating object
static method in interface
Interface supports Multiple Inheritance
• Classes in java doesn't support multiple inheritance.
• A class can implement more than one interface.
• In java, multiple inheritance is possible by using interface.
Multiple inheritance in Java by interface
• If a class implements multiple interfaces, or an interface
extends multiple interfaces, it is known as multiple inheritance.
Multiple Inheritance problem
Multiple inheritance in Java by interface
Multiple Inheritance using Interfaces
interface Moveable{ boolean isRollable() {
boolean isMoveable(); return true;
} }
Interface Rollable{ public static void main (String args[]) {
boolean isRollable(); Tyre tr=new Tyre();
} [Link]([Link]());
class Tyre implements [Link]([Link]());
Moveable, Rollable{
}
int width;
}
boolean isMoveable(){
return true;
}
Abstract class Interface
• A class which contain one or • It is a Java Object containing
more abstract methods. method declaration but no
implementation.
• Methods are implemented by • The classes which implement the
its sub classes. Interfaces must provide the method
definition.
• abstract keyword followed by
Class definition. • Starts with interface keyword.
• Used for partial abstraction. • Used for full abstraction.
• It contains abstract and • It contains all abstract methods
concrete methods. and static and final variable.
Package
83
Packages
• Packages are containers for classes.
• Classes can be defined inside a package that are not
accessible by code outside that package.
• Define class members that are exposed only to other
members of the same package.
• Packages are stored in a hierarchical manner.
• These are explicitly imported into new class definitions.
• If you omit the package statement, the class names are
put into the default package, which has no name.
Packages are stored in a hierarchical manner.
package statement
• The package statement defines a name space in which
classes are stored.
• General form of the package statement:
package package-name;
• Example:
package mypack;
public class employee
{
statement;
}
Usage of Package
• Package are used in Java to avoid name conflicts and to
control access of class and interface.
• A package can be defined as a group of similar types of
classes, interface or sub-package.
• A package is always defined as a separate folder having
the same name as the package name.
• Store all the classes in that package folder.
• All classes of the package must be declared public to
access outside the package.
• All classes within the package must have the package
statement as its first line.
• All classes of the package must be compiled before use.
Types of Packages
• Types of Packages:
-Built-in package
-User defined package
• Built-in Package:
• Existing Java package.
• Example [Link], [Link], awt, javax, swing, net, io, util, sql
etc.
• User-defined-package:
• Java package created by user to categorize their project's
classes and interface.
Package example
package pack;
public class First {
public static void main(String args[]) {
[Link]("Welcome to package");
}
How to compile Java programs inside packages?
• Compile your packages:
javac -d directory javafilename
• Run your package:
java [Link]
• Example: Package is= pack
Java file name= [Link]
• Steps:
• Compile java file with javac [Link]
• To create package with javac –d . [Link]
• Run java [Link]
Create a sub package p2 within our existing java
package pack
package pack.p2;
class File {
public void print() {
[Link](“Welcome Sub package");
}
Public static void main(String args[]) {
File F=new File();
[Link]();
}
}
How to compile Java programs inside packages?
• Steps:
• Compile java file with javac [Link]
• To create package with javac –d . [Link]
• Run java [Link]
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.
Import package
• import keyword is used to import built-in and user-defined
packages into your java source file.
• Class can refer to a class that is in another package by
directly using its name.
• There are 3 different ways to access any class present in a
different package:
-Using fully qualified name
-To import only one class from a package.
-To import all the classes from a package.
Using fully qualified name
• By using fully qualified name-
-Only a particular class of the package will be accessible.
-Other classes in the same package will not be accessible.
• No need to use the import statement.
• Use fully qualified name every time while accessing the class or
the interface.
• This is generally used when two packages have classes with
same names.
Access class using fully qualified name
//[Link] //[Link]
package mypack;
package pack; class B {
public class A { public static void main(String
args[]) {
public void msg() { pack.A obj = new pack.A();
[Link] ("Hello"); //fully qualified name
}
} [Link]();
}
}
To import only the class from a package
Import class using [Link]
only that class in the package will be available for use.
//[Link]
//[Link] package mypack;
package pack; import pack.A;
public class A { class B {
public static void main(String args[])
public void msg() { {
A obj = new A();
[Link]("Hello"); [Link]();
} }
} }
To import all the classes from a package
• Use packagename.*
• All the classes and interfaces of package will be accessible.
• The import keyword is used to make the classes and interface
of another package accessible to the current package.
• Syntax:
package p3;
import package p1.*;
To import all the classes from a package
//[Link] //[Link]
package pack; package Java;
public class First{ import pack.*;
public void print() { class Third
[Link]("Hello"); {
} public static void main(String args[])
} {
First obj = new First();
//[Link] [Link]();
package pack; Second obj 1= new Second();
public class Second{ [Link]();
public void display() { }
[Link](“Welcome"); }
}
}
How to compile and run java file
1. javac [Link]
2. javac –d . [Link]
1. javac [Link]
2. javac –d . [Link]
1. javac [Link]
2. javac –d . [Link]
3. java [Link]
End of Unit
10
1