0% found this document useful (0 votes)
4 views69 pages

Chapter 3

Chapter 3 covers key concepts of inheritance and polymorphism in Java, explaining how inheritance allows subclasses to inherit properties from superclasses, promoting code reusability and maintenance. It discusses casting objects, including upcasting and downcasting, and introduces polymorphism, which enables methods to behave differently based on the object type at runtime. The chapter also details method binding through overloading and overriding, highlighting the differences between early and late binding.

Uploaded by

firooa37
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)
4 views69 pages

Chapter 3

Chapter 3 covers key concepts of inheritance and polymorphism in Java, explaining how inheritance allows subclasses to inherit properties from superclasses, promoting code reusability and maintenance. It discusses casting objects, including upcasting and downcasting, and introduces polymorphism, which enables methods to behave differently based on the object type at runtime. The chapter also details method binding through overloading and overriding, highlighting the differences between early and late binding.

Uploaded by

firooa37
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

Chapter 3

Inheritance and Polymorphism

1
Chapter Outline
• Inheritance
• Casting
• Polymorphism
– Method Binding: Method Overriding and Overloading
• Super
• The Object Class
• Abstract Classes
• Interfaces
– Using Interfaces

2
Inheritance
• Inheritance is implemented in Java using the keyword extends.

• When class Student is a subclass of class Person, we say: Student extends Person.

• In Java terminology, a class C1 extended from another class C2 is called a subclass, and C2 is
called a superclass.

• A superclass is also referred to as a parent class, or a base class, and a subclass as a child class,
an extended class, or a derived class.

• A subclass inherits accessible data fields and methods from its superclass and may also add
new data fields and methods

• Code reusability:- Inheritance automates the process of reusing the code of the superclasses
in the subclasses.
3
Inheritance - Advantages
• With inheritance, an object can inherit its more general properties from its parent object, and
that saves the redundancy in programming.

• Code maintenance:- Organizing code into hierarchical classes makes its maintenance and
management easier.

• Implementing OOP:- Inheritance helps to implement the basic OOP philosophy to adapt
computing to the problem and not the other way around, because entities (objects) in the real
world are often organized into a hierarchy.
• Look into the example in the next slide

4
Inheritance

public class Dog { public class Cat {


private String name; private String name;
private int fleas; private int hairballs;
public Cat(String n, int h) {
public Dog(String n, int f) { name = n;
name = n; hairballs = h;
fleas = f; }
} public String getName() {
public String getName() { return name;
return name; }
} public int getHairballs() {
public int getFleas() { return hairballs;
return fleas; }
} public void speak() {
public void speak() { [Link]("Meow");
[Link]("Woof"); }
} }
} 5
Inheritance
• Problem in the previous code: Code Duplication

• Dog and Cat have the name field and the getName() method in common.

• Classes often have a lot of state and behavior in common

– Result: lots of duplicate code!

– Solution: Inheritance

• Inheritance allows you to write new classes that inherit from existing classes

• The existing class whose properties are inherited is called the "parent" or super-class

• The new class that inherits from the super class is called the "child" or subclass

• Result: Lots of code reuse!

6
Inheritance

7
Inheritance Dog Subclass
public class Dog extends Animal {
private int fleas;
Animal Superclass
public Dog(String n, int f) {
public class Animal { super(n); // calls Animal constructor
private String name; fleas = f;
public Animal(String n) { }
name = n; public int getFleas() {
} return fleas;
public String getName() { }
return name; public void speak() {
} return [Link]("Woof");
} }
}

8
Inheritance Cat Subclass

public class Cat extends Animal {


private int hairballs;
public Cat(String n, int h) {
super(n); // calls Animal constructor
hairballs = h;
}
public int getHairballs() {
return hairballs;
}
public void speak() {
return [Link]("Meow");
}
}
9
Inheritance
Quiz
What is the output of the following?
Dog d = new Dog("Rover" 3);

Cat c = new Cat("Kitty", 2);

[Link]([Link]() + " has " + [Link]() + " fleas");

[Link]([Link]() + " has " + [Link]() + " hairballs");

Output
Rover has 3 fleas
Kitty has 2 hairballs
(Dog and Cat inherit the getName method from Animal)
10
Inheritance Rules
• Use the extends keyword to indicate that one class inherits from another

• The subclass inherits all the fields and methods of the superclass

• Use the super keyword in the subclass constructor to call the superclass constructor

• The keyword super refers to the superclass of the class in which super appears. It can be used
in two ways:

– To call a superclass constructor.

– To call a superclass method.

11
Inheritance Rules
Subclass Constructor

– The first thing a subclass constructor must do is call the superclass constructor

– This ensures that the superclass part of the object is constructed before the subclass part

– If you do not call the superclass constructor with the super keyword, and the superclass
has a constructor with no arguments, then that superclass constructor will be called
implicitly.

• Implicit call only works if superclass has a no-arg constructor.

• If superclass has only parameterized constructors, subclass must explicitly call one using
super(...).

12
Inheritance Rules
Implicit Super Constructor Call then this Beef subclass:

public class Beef extends Food {


If We have this Food class:
private double weight;
public Beef(double w) {
weight = w
public class Food { }
private boolean raw; }
public Food() { is equivalent to:
raw = true;
public class Beef extends Food {
} private double weight;
} public Beef(double w) {
super();
weight = w
}
}

13
Inheritance Rules
Quiz 2
public class A {
public A() {
[Link]("I'm A");
}
} Output
public class B extends A {
public B() { I'm A
[Link]("I'm B");
} I'm B
}
public class C extends B { I'm C
public C() {
[Link]("I'm C");
}
}

What does this print out?


C x = new C();
14
Inheritance Rules
Calling Superclass Constructors

• The syntax to call a superclass constructor is:

super(), or super(parameters);

• The statement super() invokes the no-arg constructor of its superclass, and the statement
super(arguments) invokes the superclass constructor that matches the arguments.

• The statement super() or super(arguments) must appear in the first line of the subclass
constructor; this is the only way to explicitly invoke a superclass constructor.

15
public class Student extends Person {
Inheritance Rules - Calling Superclass public String branch;
Constructors - Example public int Student_id;
public Student(String name, int age, String branch, int
class Person{ Student_id){
public String name; super(name, age);
[Link] = branch;
public int age;
this.Student_id = Student_id;
public Person(String name, int age){
}
[Link] = name; public void displayStudent() {

[Link] = age; [Link]("Data of the Student class: ");


[Link]("Name: “ + [Link]);
}
[Link]("Age: “ + [Link]);
public void displayPerson() { [Link]("Branch: “ + [Link]);
[Link]("Data of the Person [Link]("Student ID: “ + this.Student_id);
}
class: ");
public static void main(String[] args) throws
[Link]("Name: "+[Link]);
CloneNotSupportedException {
[Link]("Age: "+[Link]); Person person = new Student("Krishna", 20, "IT", 1256);

} [Link]();
}
} 17
}
Casting Objects
• Objects of a class can be cast into objects of another class if both classes are related to each other
through the property of inheritance, i.e., one class is the parent/super class, and the other class is the
child/sub class. This type of casting superclass object (parent class) will hold the sub-class object's
properties.
• Java object typecasting: one object reference can be type cast into another object reference.
Conditions of Object Casting:
– Same class objects can be assigned to one another
– Subclass object can be assigned to a super class object and this casting is done implicitly. This is
known as Upcasting(upwards in the hierarchy from subclass to super class).
– Java does not permit to assign a super class object to a subclass object(Implicitly) and still to do
so, we need explicit casting. This is known as down casting( super class to sub class). Downcasting
requires Explicit casting.
18
Casting Objects
Upcasting class Parent{
void PrintData() {
• Upcasting is a type of object typecasting in [Link]("method of parent class");
}
which a child/subclass object is typecasted to }
a parent/super class object.
class Child extends Parent {
• By using the Upcasting, we can easily access void PrintData() {
the variables and methods of the [Link]("method of child class");
}
parent/super class to the child/sub class. }
• Here, we don't access all the variables and class UpcastingExample{
public static void main(String args[]) {
the method.
• We access only some specified variables and Parent obj1 = (Parent) new Child();
Parent obj2 = new Child();
methods of the child class. [Link]();
• Upcasting is also known as Generalization [Link]();
} Output
and Widening. } method of child class
method of child class 19
Casting Objects
Downcasting
• downcasting is another type of object typecasting.
• In doncasting, we assign a parent class reference object to the child class.
• In Java, we cannot assign a parent class reference object to the child class, but if we perform
downcasting, we will not get any compile-time error.
• However, when we run it, it throws the "ClassCastException".
• Now the point is if downcasting is not possible in Java, then why is it allowed by the
compiler? In Java, some scenarios allow us to perform downcasting. Here, the subclass object
is referred by the parent class.
• Below is an example of downcasting in which both the valid and the invalid scenarios are
explained:
20
Casting Objects - Downcasting - Example
//Parent class public class Downcasting{
class Parent {
String name; public static void main(String[] args)
// A method which prints the data of the parent cla {
ss Parent p = new Child();
void showMessage() [Link] = "Shubham";
{
[Link]("Parent method is called"); // Performing Downcasting Implicitly
//Child c = new Parent(); // it gives compile-
} time error
}
// Child class // Performing Downcasting Explicitly
class Child extends Parent { Child c = (Child)p;
int age;
[Link] = 18;
// Performing overriding [Link]([Link]);
@Override [Link]([Link]);
void showMessage() [Link]();
{ }
[Link]("Child method is called"); }

} Output
}
Shabha
18
method of child class is called 21
Casting Objects - Example
public class Animal {
private String name;
public Animal(String n) { public class Cat extends Animal {
name = n;
private int hairballs;
}
public String getName() { public Cat(String n, int h) {
return name; super(n); // calls Animal constructor
}
hairballs = h;
}
public class Dog extends Animal { }
private int fleas; public int getHairballs() {
public Dog(String n, int f) {
return hairballs;
super(n); // calls Animal constructor
fleas = f; }
} public void speak() {
public int getFleas() {
return [Link]("Meow");
return fleas;
} }
public void speak() { }
return [Link]("Woof");
}
}
22
Casting Objects - Example

public static void main(String[] args) {


Animal a1 = new Animal();
((Dog)a1).getFleas();
((Cat)a1).getHairballs();
((Dog)a1).speak();

Animal a2 = new Dog();


((Dog)a2).getFleas();
((Cat)a2).getHairballs();
((Dog)a2).speak();

Dog d = new Dog();


((Cat)d).getHairballs();
}

23
Polymorphism
• Polymorphism is one of the principles in Object Oriented Programming paradigm.

• The computer differentiates between (or among) methods depending on either the method
signature (after compile) or the object reference (at run time).

• The term polymorphism means “a method the same as another in spelling but with different
behavior.”

• Polymorphism is the ability of objects to act depending on the run time type.

• Polymorphism allows programmers to send the same message to objects from different
classes. i.e., in its simplest from, polymorphism allows a single variable to refer to objects
from different classes.

• Polymorphism enables us to “program in the general” rather than “program in the specific”.
24
Polymorphism - Method Binding
• In general, connecting a method call to a method body is called binding.

• When binding is performed before the program is run, it’s called early binding. also called
[static binding] OR [compile-time binding]

• When the binding occurs at run-time based on the type of object, it’s called late binding. also
called [dynamic binding] OR [run-time binding.]

• When late binding is implemented, there must be some mechanism to determine the type of
the object at run-time and to call the appropriate method.

• That is, the compiler still doesn’t know the object type, but the method-call mechanism finds
out and calls the correct method body.

25
Polymorphism - Implementation of method binding (Polymorphism)
• Method binding can be done through: overloading and overriding
Method Overloading (Early Binding) static binding
– Methods whose headings differ in the number and type of formal parameters are said to be overloaded
methods.
– Methods with same name, but the compiler uses two mechanisms to differentiate the overloaded methods
1. Number of parameters
2. Datatype of parameters
Method Overriding (Late Binding) dynamic binding
– Methods with same name and signature and applied on inheritance concepts.
– Methods of a subclass override the methods of a super class in a given inheritance hierarchy.
– Methods of a subclass implement the abstract methods of an abstract class.
– Methods of a concrete class implement the methods of an interface.
– Run-time polymorphism comes in two different forms: run-time polymorphism with abstract base
classes and run-time polymorphism with interfaces.
– Sometimes run-time polymorphism is referred to as dynamic binding.
26
Polymorphism - using overloaded methods Example

public class DemoClass


// A Java program written to demonstrate
{
compile-time
public int add(int x, int y)
// polymorphism using overloaded methods
{
public class OverLoaded
return x + y;
{
}
public static void main(String [] args)
// end add(int, int)
{
public int add(int x, int y, int z)
DemoClass obj = new DemoClass();
{
[Link]([Link](2,5)); // int, int
return x + y + z;
[Link]([Link](2, 5, 9)); // int,
}
int, int
// end add(int, int, int)
[Link]([Link](3.14159, 10)); //
public int add(double pi, int x)
double, int
{
} // end main
return (int)pi + x;
}// end OverLoaded
}// end add(double, int)
}// end DemoClass
27
Polymorphism - using overloaded methods Example
• This form of polymorphism is called early-binding (or compile-time) polymorphism because
the computer knows after the compile to the byte code which of the add methods it will
execute.
• That is, after the compile process when the code is now in byte-code form, the computer
will “know” which of the add methods it will execute.
• If there are two actual int parameters the computer will know to execute the add method
with two formal int parameters, and so on.
• Methods whose headings differ in the number and type of formal parameters are said to be
overloaded methods.
• The parameter list that differentiates one method from another is said to be the method
signature list.

28
Polymorphism - using overriding methods in inheritance hierarchy
• In Java, method overriding occurs when a subclass (child class) has the same method as the
parent class.

• In other words, method overriding occurs when a subclass provides a particular implementation
of a method declared by one of its parent classes.

• There is another form of polymorphism called late-binding (or run-time) polymorphism because
the computer does not know at compile time which of the methods are to be executed.

• It will not know that until “run time.” Run-time polymorphism is achieved through what are called
overridden methods (while compile-time polymorphism is achieved with overloaded methods).

• Run-time polymorphism comes in two different forms: run-time polymorphism with abstract
base classes and run-time polymorphism with interfaces.

• Sometimes run-time polymorphism is referred to as dynamic binding.


29
Polymorphism - using overriding methods Example 1
Method print in Dog and Method print in Cat override method print in Animal
public class Animal{
void print(){ public static void main(String args[]){
[Link]("Superclass Animal animal = new Animal();
Animal"); Dog dog =new Dog();
} } Cat cat =new Cat();
class Dog extends Animal{ [Link]();
void print(){ [Link]();
[Link]("Subclass Dog"); [Link]();
} } }
class Cat extends Animal{ } Output
void print(){ Superclass Animal
[Link]("Subclass Cat"); Subclass Dog
} Subclass Cat 30
Polymorphism - using overriding methods Example 2
In the below code, void engine() within Vehicle class is called overridden method. The void engine() method within
Bike Class and Car Class is called the overriding method.

Output
this is bike engine
this is car engine

31
Super
• 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

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

32
Super: 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(){
[Link](color); //prints color of Dog class
[Link]([Link]); //prints color of Animal class
}
}
Output
Black
class TestSuper1{
White
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}
} 33
Super: 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. class Animal{
void eat(){
[Link]("eating...");
}
}
class Dog extends Animal{
void eat(){ Output
[Link]("eating bread...");}
void bark(){
eating
[Link]("barking...");} barking
void work(){
[Link]();
bark();
} }
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
} } 34
Super: 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(){
[Link]("animal is created");
} }
class Dog extends Animal{
Dog(){
Output
super(); animal is created
[Link]("dog is created"); dog is created
} }
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
35
The Object Class
• All Java classes implicitly inherit from [Link]. In Java, [Link] is the root
class of the class hierarchy.

• This makes Object the ultimate superclass of all Java classes.

• So, every class you write will automatically have methods in Object such as equals, hashCode,
and toString.

• If no inheritance is specified when a class is defined, the superclass of the class is Object by
default. For example, the following two class definitions are the same:

36
The Object Class: Methods of Object class
• The Object class provides many methods. They are as follows:
Method Description

public final Class getClass() returns the Class class object of this object. The Class class can further be used to get the metadata of this
class.

public int hashCode() returns the hashcode number for this object.

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

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

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's monitor.

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

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

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

protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage collected.
37
Abstraction

• In object-oriented programming abstraction is a process of hiding the implementation details


from the user, only the functionality will be provided to the user.

• In other words, user will have the information on what the object does instead of how it does.

• In Java Abstraction is achieved using

• Abstract classes,

• Abstract methods and

• Interfaces.

38
Abstract Methods
• If you want a class to contain a particular method but you want the actual implementation of
that method to be determined by child classes, you can declare the method in the parent
class as abstract.

• abstract keyword is used to declare the method as abstract.

• An abstract method contains a method signature, but no method body.

• Instead of curly braces an abstract method will have a semicolon ( ; ) at the end.

Syntax:
<access specifier> abstract <return type> <methodName>(para_list);
Example:
public abstract void calculateArea();
39
Abstract Classes
• In the inheritance hierarchy, classes become more specific and concrete with each new subclass.
• If you move from a subclass back up to a superclass, the classes become more general and less
specific.
• Class design should ensure that a superclass contains common features of its subclasses.
• Sometimes a superclass is so abstract that it cannot have any specific instances.
• Such a class is referred to as an abstract class.
Points to Remember
• 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. 40
Abstract Classes
• A class which contains the abstract keyword in its declaration is known as abstract class.

• Abstract classes may or may not contain abstract methods [methods with out body

public void get(); – only declaration of a method.

• But, if a class have at least one abstract method, then the class must be declared as abstract.

• If you inherit an abstract class you have to provide implementations to all the abstract
methods in it.

41
Abstract Classes – Example Scenario
• Suppose we were modeling the behavior of animals, by creating a class hierarchy that started
with a base class called Animal.

• Animals are capable of doing different things like flying, digging and walking, but there are
some common operations as well like eating and sleeping.

• Some common operations are performed by all animals, but in a different way as well.

• When an operation is performed in a different way, it is a good candidate for an abstract


method (forcing subclasses to provide a custom implementation).

• Let's look at a very primitive Animal base class, which defines an abstract method for making
a sound (such as a dog barking, a cow mooing etc.).

42
Abstract Class - Example
public abstract Class Animal {
public void eat(String fd) {
// do something
}
public void sleep(int hours) {
// do something
}
// signature of abstract method
public abstract void makeNoise();
}
public class Cat extends Animal{
//implementation of abstract method
void makeNoise() {
[Link](“meow”);
}}
public class Dog extends Animal{
//implementation of abstract method
void makeNoise() {
[Link](“wuuwuu”);
}
}
43
Abstract Classes - Understanding the real scenario of Abstract class
abstract class Shape{
• In this example, Shape is the abstract abstract void draw();
}
class, and its implementation is provided //In real scenario, implementation is provided by others
i.e. unknown by end user
by the Rectangle and Circle classes. class Rectangle extends Shape{
void draw(){[Link]("drawing rectangle");}
• Mostly, we don't know about the }
class Circle1 extends Shape{
implementation class (which is hidden to
void draw(){[Link]("drawing circle");}
the end user), and an object of the }
//In real scenario, method is called by programmer or us
implementation class is provided by the er
class TestAbstraction1{
factory method. public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is
• In this example, if you create the instance provided through method, e.g., getShape() method
[Link]();
of Rectangle class, draw() method of }
}
Rectangle class will be invoked.
Output
44
drawing circle
Static
Static keyword used when instances or methods needs to be common to all the objects of a
class.
• Can be used with:
• Variables
• Methods
• Classes
• Static variable: used to store data that is common to the entire class
– single copy of the data will be shared by all instances
– known as class variables
Syntax:
<<access specifier>> static <<Datatype>> <<variable name>>
Example: public static int counter;
• Accessibility: if access specifier is private, it can be accessed only within the class. In case of other access specifier,
it can be accessed using class name or through object reference
45
Static Variable Example

public class customer { public static void main(String[] args)


private int custID; {
// static variable customer cust1=new customer();
public static int counter=0; [Link]("1-Customer ID:
public customer() "+[Link]());
{ customer cust2=new customer();
custID=++counter; [Link]("2-Customer ID:
} "+[Link]());
public int getCustID() [Link]("Total number of customers are:
{ "+counter);
return custID; }
} }
46
Static methods
• Generic to the entire class
• Used for accessing the static variables and invoke static methods of the class
• Can be invoked using class name; object reference can also be used
Syntax:
<<access specifier>> static <<return datatype>><<method name()>> { <<code inside
the method>> }
Accessibility:
– class_name.method_name();
– object_name.method_name();
Rules:
– Static methods can access only static variables and other static methods
– Cannot access the non static variables and methods directly in side the static method
– To access non static variables and methods inside the static methods we have to use
objects
47
Static Method Example
public class staticMethod{
public static void main(String args[]) {
static int i;
//Its a Static Method
static String s;
{
//Static method
staticMethod obj=new staticMethod();
static void display() //Static method called in another static
{ method
[Link]("static method display"); display();
} //non-static method called in another static
void funcn() method

{ obj. funcn();
//Static method called in non-static method }
display(); }
} }
48
Static Class
• A Class can be made static only if it is a nested Class (inner class)

• The nested static class can be accessed without having an object of outer class.

• static class can access only static variables. [if the inner class has static variables or methods,
it should be static.]

• Using class name, we can access only static methods.

• If the method is non-static, we have to create object for static class.

Syntax:
static class <<className>> {

code inside the class>>

49
Static Class Example
public static void main(String args[]){
MyInnerClassDemo innerr=new
MyInnerClassDemo();

public class MyOuterClassDemo { [Link]();

private static int x= 1; }

// static inner class definition }

static class MyInnerClassDemo { // end outer class definition

public void seeOuter () {


//the variable should be static
[Link]("Outer Value of x is :" + x);
} }
// end inner class definition

50
Final Example

• Final keyword can be used with class Demo{


final int MAX_VALUE=99;
– variables
void myMethod(){
– methods MAX_VALUE=101; //error: cannot re-
initialize final variables
– Classes
}
public static void main(String args[]){
Demo obj=new Demo();
Final variable
[Link]();
• Final variables are constants. } }

• We cannot change the value of a final variable once it is initialized.

• Cannot re-initialize final variables

51
Final Method - Example
Example 1 Example 2

class XYZ{ class XYZ{


final void demo(){ final void demo()
[Link]("XYZ Class Method");
{
} }
[Link]("XYZ Class Method");
class ABC extends XYZ{
} }
void demo(){
[Link]("ABC Class Method");
} class ABC extends XYZ{
public static void main(String args[]){ public static void main(String args[]){
ABC obj= new ABC(); ABC obj= new ABC();
[Link](); [Link]();
} } } }
Error: demo() in ABC cannot override demo() in
Output: XYZ Class Method
XYZ 52
Final Class
• We cannot extend a final class.
final class XYZ{
}
class ABC extends XYZ{
void demo(){
[Link]("My Method");
}
public static void main(String args[]){
ABC obj= new ABC();
[Link]();
}
}
Error: cannot inherit from final XYZ
53
Final - Points to Remember
1. A constructor cannot be declared as final.

2. Local final variable must be initializing during declaration.

3. All variables declared in an interface are by default final.

4. We cannot change the value of a final variable.

5. A final method cannot be overridden.

6. A final class not be inherited.

7. If method parameters are declared final then the value of these parameters cannot be
changed.

8. It is a good practice to name final variable in all CAPS.

54
Interfaces
• An interface is a reference type in Java, it is similar to class, it is a collection of abstract
methods and static & final variables.

• 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

55
Interfaces
• An interface is a classlike construct that contains only constants and abstract methods.

• In many ways an interface is similar to an abstract class, but its intent is to specify common
behavior for objects.

• To distinguish an interface from a class, Java uses the following syntax to define an interface:

Syntax Here is an example of an interface:


modifier interface InterfaceName {
public interface Edible {
/** Constant declarations */
/** Method signatures */
/** Describe how to eat */
} public abstract String howToEat();
}
56
Interfaces
• An interface is treated like a special class in Java.

• Each interface is compiled into a separate bytecode file, just like a regular class.

• As with an abstract class, you cannot create an instance from an interface using the new
operator, but in most cases, you can use an interface more or less the same way you use an
abstract class.

• For example, you can use an interface as a data type for a reference variable, as the result of
casting, and so on.

• The relationship between the class and the interface is known as interface inheritance.

• Since interface inheritance and class inheritance are essentially the same, we will simply refer
to both as inheritance.
57
Interfaces - Example

interface Vehicle {
void start();
void stop();
• The Car class implements
default void blowHorn() { the Vehicle interface.
[Link]("Blowing horn");
} • It must provide concrete
}
implementations for all
class Car implements Vehicle {
public void start() { abstract methods.
[Link]("Starting engine...");
}
• It can optionally use or
public void stop() { override the default method
[Link]("Stopping engine...");
} blowHorn()
}

58
Interfaces
• Interfaces are used to achieve:

– Abstraction: Hide implementation details

– Multiple inheritance: A class can implement multiple interfaces

• Key Concepts

– Polymorphism: Interfaces allow you to write flexible code that works with any class
implementing the interface.

– Loose coupling: Interfaces help decouple components, making your code easier to
maintain and test.

– Design patterns: Many patterns like Strategy, Observer, and Factory rely heavily on
interfaces.
59
Interfaces have the following properties:
• An interface is implicitly abstract.

• You do not need to use the abstract keyword while declaring an interface.

• Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.

• Methods in an interface are implicitly public.

• In Java, you cannot implement a method inside an interface unless you use one of these
keywords:

– default - Allows instance methods with a body

– static - Allows static utility methods with a body

– private - Allows helper methods used by other default methods

60
Implementing Interfaces
• When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface.

• If a class does not perform all the behaviors of the interface, the class must declare itself as
abstract.

• A class uses the implements keyword to implement an interface.


<<access specifier>>class<<className>> implements <<interfaceName>>{}

• A class can implement more than one interfaces


<<access specifier>>class<<className>> implements <<interface1Name>> , <<interface2Name>> {}

• Implementing an interface is like signing a contract with the compiler that states “ I will define
all the method specified by the interface or I will declare my class abstract”
61
Implementing Interfaces - Example //Interface declaration: by first user
interface Drawable{
• In this example, the Drawable interface void draw();
}
has only one method. //Implementation: by second user
class Rectangle implements Drawable{
• Its implementation is provided by public void draw(){[Link]("drawing rect
angle");}
Rectangle and Circle classes. }
class Circle implements Drawable{
• In a real scenario, an interface is public void draw(){[Link]("drawing circ
le");}
defined by someone else, but its }
//Using interface: by third user
implementation is provided by class TestInterface1{
public static void main(String args[]){
different implementation providers. Drawable d=new Circle();//In real scenario, object
is provided by method e.g. getDrawable()
• Moreover, it is used by someone else. [Link]();
}
The implementation part is hidden by }

the user who uses the interface. Output:


drawing circle 62
Extending Interfaces
• When implementation interfaces there are several rules:

• A class can implement more than one interface at a time.

• A class can extend only one class, but implement many interfaces.

• An interface can extend another interface, similarly to the way that a class can extend
another class.

• The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.
<<access specifier>>interface<<interfaceName>> extends <<super_interfaceName>> {}

63
Extending Multiple Interfaces
• A Java class can only extend one parent class.

• Multiple inheritance is not allowed.

• Interfaces are not classes, however, and an interface can extend more than one parent
interface.

• The extends keyword is used once, and the parent interfaces are declared in a comma-
separated list.

<<access specifier>>interface<<interfaceName>> extends


<<super_interfaceName>> , <<super_interfaceName2>> {}

64
Extending Multiple Interfaces
• An interface can inherit other interfaces using the extends keyword. Such an interface is called
a subinterface.

• For example, NewInterface in the following code is a subinterface of Interface1, and


InterfaceN.
public interface NewInterface extends Interface1, ..., InterfaceN {

// constants and abstract methods

• A class implementing NewInterface must implement the abstract methods defined in


NewInterface, Interface1, and InterfaceN. An interface can extend other interfaces but not
classes.

• A class can extend its superclass and implement multiple interfaces.


65
Extending Interfaces
• All classes share a single root, the Object class, but there is no single root for interfaces.
• Like a class, an interface also defines a type. A variable of an interface type can reference any
instance of the class that implements the interface.
• If a class implements an interface, the interface is like a superclass for the class.
• You can use an interface as a data type and cast a variable of an interface type to its subclass,
and vice versa.
• In general, interfaces are preferred over abstract classes because an interface can define a
common supertype for unrelated classes. Interfaces are more flexible than classes. Consider
the Animal class.
• Interfaces don’t have this restriction. Interfaces give you more flexibility than classes, because
you don’t have make everything fit into one type of class.
66
Extending Interfaces
• You may define the howToEat() method in an interface and let it serve as a common supertype
for other classes. For example,

• To define a class that represents edible objects, simply let the class implement the Edible interface. The class is
now a subtype of the Edible type. Any Edible object can be passed to invoke the eat method.
67
Using Interfaces
• To create an interface, use the interface keyword instead of the class keyword.
• As with a class, you can add the public keyword before the interface keyword (but only if that
interface is defined in a file of the same name).
• If you leave off the public keyword, you get package access, so the interface is only usable
within the same package.
• An interface can also contain fields, but these are implicitly static and final.
• To make a class that conforms to a particular interface, use the implements keyword, which
says, "The interface is what it looks like, but now I’m going to say how it works." Other than
that, it looks like inheritance.
• Once you have implemented an interface, that implementation becomes an ordinary class
that can be extended in the regular way.
68
Using Interfaces
• You can choose to explicitly declare the methods in an interface as public, but they are public even if
you don’t say it.

• So, when you implement an interface, methods from the interface must be defined as public.

• Otherwise, they would default to package access, and you are reducing the accessibility of a method
during inheritance, which is not allowed by the Java compiler.

• Note that every method in the interface is strictly a declaration, which is the only thing the compiler
allows.

Why do we use Interfaces?

• To have unrelated classes implement similar methods

• Example: Class PDF and Music – Not related – Both implements download methods -- isDownload

• To model multiple inheritance which allows a class to have more than one superclass
69
Interfaces – Example 2
public interface Relation {
public boolean isDownload();
}
class PDF implements Relation {
public boolean isDownload() Class test{
{ public static void main(String[] args) {
[Link](“PDF download”);
PDF p= new PDF();
}
[Link]();
}
}
class music implements Relation {
}
public boolean isDownload()
{
[Link](“PDF download”);
}
}
70

You might also like