Java 3rd Module Notes
Java 3rd Module Notes
UNIVERSITY
JNANA SANGAMA, BELGAVI-590018, KARNATAKA
Object Oriented
Programming with
JAVA
(AS PER CBCS SCHEME 2022)
PREPARED BY:
LAVANYA S
ASSISTANT PROFESSOR
Module :03
Inheritance: Inheritance Basics, Using super, Creating a Multilevel Hierarchy,
When Constructors Are Executed, Method Overriding, Dynamic Method
Dispatch, Using Abstract Classes, Using final with Inheritance, Local Variable
Type Inference and Inheritance, The Object Class.
Interfaces: Interfaces, Default Interface Methods, Use static Methods in an
Interface, Private Interface Methods.
Inheritance in Java
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the
mechanism in Java by which one class is allowed to inherit the features(fields and methods)
of another class. In Java, Inheritance means creating new classes based on existing ones. A
class that inherits from another class can reuse the methods and fields of that class.
Example: In the following example, Animal is the base class and Dog, Cat and Cow are
derived classes that extend the Animal class.
Implementation:
// Parent class
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
// Child class
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
// Child class
class Cat extends Animal {
1
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
void sound() {
[Link]("Cat meows");
}
}
// Child class
class Cow extends Animal {
void sound() {
[Link]("Cow moos");
}
}
// Main class
public class Geeks {
public static void main(String[] args) {
Animal a;
a = new Dog();
[Link]();
a = new Cat();
[Link]();
a = new Cow();
[Link]();
}
}
Output
Dog barks
Cat meows
Cow moos
2
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
Explanation:
• Animal is the base class.
• Dog, Cat and Cow are derived classes that extend Animal class and provide specific
implementations of the sound() method.
• The Geeks class is the driver class that creates objects and demonstrates runtime
polymorphism using method overriding.
Note: In practice, inheritance and polymorphism are used together in Java to achieve fast
performance and readability of code.
Syntax
class ChildClass extends ParentClass {
3
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
Below are the different types of inheritance which are supported by Java.
• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Multiple Inheritance
• Hybrid Inheritance
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes, it is also known as simple
inheritance.
Example:
//Super class
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}
// Subclass
class Car extends Vehicle {
Car() {
[Link]("This Vehicle is Car");
}
}
public class Test {
public static void main(String[] args) {
// Creating object of subclass invokes base class constructor
4
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
Output
This is a Vehicle
This Vehicle is Car
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also acts as the base class for other classes.
Example:
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}
class FourWheeler extends Vehicle {
FourWheeler() {
[Link]("4 Wheeler Vehicles");
}
}
class Car extends FourWheeler {
Car() {
[Link]("This 4 Wheeler Vehicle is a Car");
}
}
public class Geeks {
public static void main(String[] args) {
5
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
Output
This is a Vehicle
4 Wheeler Vehicles
This 4 Wheeler Vehicle is a Car
3. Hierarchical Inheritance
In hierarchical inheritance, more than one subclass is inherited from a single base class. i.e.
more than one derived class is created from a single base class. For example, cars and buses
both are vehicle
Example:
class Vehicle {
Vehicle() {
[Link]("This is a
Vehicle");
}
}
class Car extends Vehicle {
Car() {
[Link]("This Vehicle is Car");
}
}
class Bus extends Vehicle {
Bus() {
[Link]("This Vehicle is Bus");
}
}
6
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
Output
This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus
7
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
Output
This is an AmphibiousVehicle
This is a WaterVehicle
This is a LandVehicle
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. In Java, we can achieve hybrid
inheritance only through Interfaces if we want to involve multiple inheritance to implement
Hybrid inheritance.
Explanation:
• class Car extends Vehicle->Single Inheritance
class Bus extends Vehicle and class Bus extends Fare->Hybrid Inheritance (since Bus
inherits from two sources, forming a combination of single + multiple inheritance).
8
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
class SolarSystem {
}
class Earth extends SolarSystem {
}
class Mars extends SolarSystem {
}
public class Moon extends Earth {
public static void main(String args[])
{
SolarSystem s = new SolarSystem();
Earth e = new Earth();
Mars m = new Mars();
[Link](s instanceof SolarSystem);
[Link](e instanceof Earth);
[Link](m instanceof SolarSystem);
}
}
Output
true
true
true
Advantages of Inheritance in Java
• Code Reusability: Inheritance allows for code reuse and reduces the amount of code
that needs to be written. The subclass can reuse the properties and methods of the
superclass, reducing duplication of code.
• Abstraction: Inheritance allows for the creation of abstract classes that define a
common interface for a group of related classes. This promotes abstraction and
encapsulation, making the code easier to maintain and extend.
9
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
• Class Hierarchy: Inheritance allows for the creation of a class hierarchy, which can be
used to model real-world objects and their relationships.
• Polymorphism: Inheritance allows for polymorphism, which is the ability of an object
to take on multiple forms. Subclasses can override the methods of the superclass,
which allows them to change their behavior in different ways.
Disadvantages of Inheritance in Java
• Complexity: Inheritance can make the code more complex and harder to understand.
This is especially true if the inheritance hierarchy is deep or if multiple inheritances is
used.
• Tight Coupling: Inheritance creates a tight coupling between the superclass and
subclass, making it difficult to make changes to the superclass without affecting the
subclass.
Using super
The super keyword is used to refer to the immediate parent class object.
It allows a child class to access parent class members (variables, methods, and
constructors).
Why do we use super?
1. Call the parent class constructor
2. Access parent class variables when they are hidden by child variables
3. Call parent class methods that are overridden in the child class
Using super to Access Parent Variables
Sometimes the child class has a variable with same name as the parent class.
In that case, super helps to access the parent’s variable.
Example
class Parent {
int x = 100;
}
class Child extends Parent {
int x = 200;
void display() {
[Link]("Child x = " + x);
10
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
11
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
12
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
}
class Child extends Parent {
Child() {
super(); // optional (added automatically)
[Link]("Child Constructor");
}
}
class Test {
public static void main(String[] args) {
Child c = new Child();
}
}
Output
Parent Constructor
Child Constructor
Example:
Student s = new Student();
At this moment, the Student constructor executes automatically.
Order of Execution in Inheritance
If a class extends another class, constructor execution happens in the following order:
13
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
class Test {
public static void main(String[] args) {
Child c = new Child();
}
}
Output
Parent Constructor
Child Constructor
Explanation:
• When new Child() is executed, JVM first runs Parent(), then Child().
• This is because super() is added automatically.
14
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
METHOD OVERRIDING
Method overriding is the process in which a subclass defines a method with the same name,
same parameters, and same return type as the method in its superclass to provide a new or
specialized implementation.
Overriding occurs when:
A method in the subclass has
✔ the same name
✔ same parameter list
✔ same return type
as the method in the parent class.
The child class modifies or replaces the behavior of the parent method.
15
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
16
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
• An overridden method is executed based on the actual object’s type, not the
reference type
Java checks the object’s type at runtime and decides which method version to call.
Key Points
• Overriding must be present
• Parent reference → Child object
• JVM selects method during runtime
• Reference type does NOT decide method execution
• Object type decides which method executes
17
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
class Dispatch {
public static void main(String[] args) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // reference variable of type A
r = a; // r refers to A object
[Link](); // calls A's version
r = b; // r refers to B object
[Link](); // calls B's version
r = c; // r refers to C object
[Link](); // calls C's version
}
}
Output
Inside A's callme method
Inside B's callme method
Inside C's callme method
Explanation of Output
1. r = a;
o r refers to object of A
o A’s callme() executes
2. r = b;
o r refers to object of B
o B’s overridden callme() executes
3. r = c;
o r refers to object of C
o C’s overridden callme() executes
18
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
Even though the reference type is A, the object type decides which method executes.
19
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
// normal method
void sleep() {
[Link]("Animal is sleeping");
}
}
// Child class Dog
class Dog extends Animal {
// implementing abstract method
void sound() {
[Link]("Dog barks");
}
}
// Main class
public class AbstractDemo {
public static void main(String[] args) {
Output
Copy code
Dog barks
Animal is sleeping
20
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
21
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
// The following class is illegal. class B extends A { // ERROR! Can't subclass A //...
}
22
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
void sound() {
[Link]("Dog barks");
}
}
class TestVarInheritance {
public static void main(String[] args) {
// Using var
var d = new Dog(); // type inferred as Dog
[Link](); // Dog’s version runs
// Using parent reference
Animal a = new Dog(); // upcasting
[Link](); // Dog’s version runs (Dynamic Dispatch)
}
}
Output:
Dog barks
Dog barks
Method Purpose
23
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
Method Purpose
EXAMPLE
class Student {
int roll;
String name;
Student(int roll, String name) {
[Link] = roll;
[Link] = name;
}
// Overriding toString()
public String toString() {
return "Roll: " + roll + ", Name: " + name;
}
// Overriding equals()
public boolean equals(Object obj) {
Student s = (Student) obj;
return [Link] == [Link] && [Link]([Link]);
24
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
}
}
public class ObjectClassExample {
public static void main(String[] args) {
Interfaces
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.
Example:
• A remote control interface says you must have on() and off() functions.
• How the TV or AC performs these actions is decided in the implementing classes.
•
25
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
Syntax of an Interface
interface InterfaceName {
void method1();
void method2();
Example
interface Animal {
void eat();
[Link]("Dog barks");
class Demo {
[Link]();
[Link]();
26
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
Output
Dog barks
Feature Explanation
Methods Abstract by default (till Java 7)
Variables public, static, final by default
Access Modifier Interface methods must be public when implemented
Multiple Inheritance A class can implement many interfaces
Constructor Interfaces cannot have constructors
interface A {
void show();
interface B {
void display();
class C implements A, B {
[Link]("From A");
[Link]("From B");
27
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
class Demo {
[Link]();
[Link]();
interface Test {
Static Methods
interface Test {
28
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
Example
interface PaymentGateway {
class Demo{
[Link](500);
29
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
Key Features
3. They allow API evolution and support new features like Streams and Lambdas.
30
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
interface TestInterface {
// abstract method
// default method
[Link](a*a);
[Link](4);
[Link]();
31
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
Key Features
4. The scope of the static method is limited to the interface in which it is defined.
Syntax
interface InterfaceName {
// method body
Example
interface NewInterface {
// static method
32
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
// Implementation Class
[Link]();
@Override
[Link](str);
Output
33
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
Eg:
interface Demo {
instanceHelper(); // allowed
34
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A
staticHelper(); // allowed
// Implementing class
[Link]();
[Link]();
OUTPUT
35
DEPT. OF CSE-DS,KNSIT