Chapter 3
Chapter 3
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
• Dog and Cat have the name field and the getName() method in common.
– 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
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
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:
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.
• If superclass has only parameterized constructors, subclass must explicitly call one using
super(...).
12
Inheritance Rules
Implicit Super Constructor Call then this Beef subclass:
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");
}
}
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]();
}
} 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
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
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.
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.
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.
• 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 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 other words, user will have the information on what the object does instead of how it does.
• Abstract classes,
• 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.
• 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
• 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.
• 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
{ 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.]
Syntax:
static class <<className>> {
49
Static Class Example
public static void main(String args[]){
MyInnerClassDemo innerr=new
MyInnerClassDemo();
50
Final Example
51
Final Method - Example
Example 1 Example 2
7. If method parameters are declared final then the value of these parameters cannot be
changed.
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.
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:
• 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:
• 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.
• In Java, you cannot implement a method inside an interface unless you use one of these
keywords:
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.
• 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 }
• 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.
• 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.
64
Extending Multiple Interfaces
• An interface can inherit other interfaces using the extends keyword. Such an interface is called
a subinterface.
• 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.
• 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