0% found this document useful (0 votes)
2 views36 pages

Java 3rd Module Notes

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, focusing on inheritance, method overriding, and the use of the 'super' keyword. It explains different types of inheritance, including single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance, along with their implementations and examples. Additionally, it discusses the advantages and disadvantages of inheritance, the execution order of constructors, and dynamic method dispatch.

Uploaded by

lavanyas
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)
2 views36 pages

Java 3rd Module Notes

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, focusing on inheritance, method overriding, and the use of the 'super' keyword. It explains different types of inheritance, including single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance, along with their implementations and examples. Additionally, it discusses the advantages and disadvantages of inheritance, the execution order of constructors, and dynamic method dispatch.

Uploaded by

lavanyas
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

VISVESVARAYA TECHNOLOGICAL

UNIVERSITY
JNANA SANGAMA, BELGAVI-590018, KARNATAKA

Object Oriented
Programming with
JAVA
(AS PER CBCS SCHEME 2022)

SUB CODE: BCS306A

PREPARED BY:
LAVANYA S

ASSISTANT PROFESSOR

DEPT OF CSE-(DS), KNSIT

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING (DATA SCIENCE)


K.N.S INSTITUTE OF TECHNOLOGY
HEGDE-NAGAR, KOGILU ROAD,
THIRUMENAHALLI, YELAHANKA,
BANGALORE-560064
OOPS WITH JAVA BCS306A

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 {

// Additional fields and methods


}
Note: In Java, inheritance is implemented using the extends keyword. The class that inherits
is called the subclass (child class) and the class being inherited from is called the superclass
(parent class).

Types of Inheritance in Java

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

Car obj = new Car();


}
}

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

Car obj = new Car(); // Triggers all constructors in order


}
}

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

public class Test {


public static void main(String[] args) {
Car obj1 = new Car();
Bus obj2 = new Bus();
}
}

Output
This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus

4. Multiple Inheritance (Through Interfaces)


In Multiple inheritances, one class can have more than one superclass and inherit features
from all parent classes.
Note: that Java does not support multiple inheritances with classes. In Java, we can achieve
multiple inheritances only through Interfaces.
Example:
interface LandVehicle {
default void landInfo() {
[Link]("This is a
LandVehicle");
}
}
interface WaterVehicle {
default void waterInfo() {
[Link]("This is a WaterVehicle");
}
}

7
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

// Subclass implementing both interfaces


class AmphibiousVehicle implements LandVehicle, WaterVehicle {
AmphibiousVehicle() {
[Link]("This is an AmphibiousVehicle");
}
}
public class Test {
public static void main(String[] args) {
AmphibiousVehicle obj = new AmphibiousVehicle();
[Link]();
[Link]();
}
}

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

[Link]("Parent x = " + super.x);


}
}
class Test {
public static void main(String[] args) {
Child c = new Child();
[Link]();
}
}
Output
Child x = 200
Parent x = 100
Explanation
• x in Child hides x in Parent
• super.x helps to access the parent’s value

Using super to Call Parent Class Method


When a method is overridden in the child class, we can still call the parent method
using super.
Example
class Parent {
void show() {
[Link]("Parent Show");
}
}
class Child extends Parent {
@Override
void show() {

11
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

[Link](); // calling parent method


[Link]("Child Show");
}
}
class Test {
public static void main(String[] args) {
Child c = new Child();
[Link]();
}
}
Output
Parent Show
Child Show
Explanation
• Child class overrides show()
• [Link]() calls parent version
• Then child version executes
• Helps reuse parent functionality

Using super() to Call Parent Class Constructor


super() is used inside a child constructor to call the parent class constructor.
• super() must be the first statement in the constructor
• If not written, Java automatically adds super()
Example
class Parent {
Parent() {
[Link]("Parent Constructor");
}

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

WHEN CONSTRUCTORS ARE EXECUTED


A constructor in Java is a special member method used to initialize objects. It is
automatically executed at the time of object creation. It has the same name as the class and
no return type.
Meaning of Constructor Execution
When an object is created using the new keyword, the JVM immediately calls the
constructor. This ensures that all variables and objects inside the class are initialized properly
before the object is used.

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

Parent class constructor → Child class constructor


Java always executes the parent constructor first to ensure the parent part of the object is
built before the child adds its own features.
Java does this automatically using an invisible call to super() inside the child constructor.
Example – Constructor Execution
class Parent {
Parent() {
[Link]("Parent Constructor");
}
}

class Child extends Parent {


Child() {
[Link]("Child Constructor");
}
}

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

Explicit Use of super()


The child constructor may call the parent constructor explicitly:
Child() {
super();
[Link]("Child Constructor");
}
Important Points
• Constructors run automatically during object creation.
• Parent constructor executes before child.
• Constructors cannot be inherited.
• Constructors cannot be overridden, but can be overloaded.
• They are primarily used for initialization.

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.

Rules for Method Overriding


1. Method name must be same.
2. Parameter list must be same.
3. Return type must be same (or covariant).
4. Only non-static methods can be overridden.
5. Access modifier cannot be more restrictive.

15
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

6. The method must not be final or private.

7. Must be in an inheritance relationship.


Example
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
class Test {
public static void main(String[] args) {
Animal obj = new Dog(); // runtime polymorphism
[Link]();
}
}
Output
Dog barks

Dynamic Method Dispatch


Dynamic Method Dispatch is the mechanism in Java by which a call to an overridden method
is resolved at runtime, not at compile time.
It occurs when:
• A superclass reference variable refers to a subclass object (this is called upcasting)

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

Example: Dynamic Method Dispatch


class A {
void callme() {
[Link]("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
[Link]("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
[Link]("Inside C's callme method");
}
}

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.

Using Abstract Classes


An abstract class in Java is a class declared with the keyword abstract that cannot be
instantiated.
It may contain abstract methods (without implementation) and concrete methods (with
implementation).
It provides a common base for subclasses and supports abstraction and polymorphism.
Why Do We Use Abstract Classes?
We use an abstract class when:
• We want to provide a common template for all subclasses.
• Some methods must be implemented differently in child classes.
• We want to force subclasses to implement certain methods.
Syntax
abstract class ClassName {
abstract void method1(); // abstract method (no body)
void normalMethod() { // concrete method
// method body
}
}
class Child extends ClassName {
void method1() {
// child class provides implementation
}
}
EXAMPLE
// Abstract class
abstract class Animal {
// abstract method
abstract void sound();

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) {

// Animal a = new Animal(); // Not allowed: Abstract class cannot be instantiated

Animal d = new Dog(); // ✔ Upcasting allowed


[Link](); // Dog’s sound()
[Link](); // Parent normal method
}
}

Output
Copy code
Dog barks
Animal is sleeping

20
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

Using final with Inheritance


The keyword final has two uses. This use was described in the preceding chapter. The uses
of final apply to inheritance. Both are examined here.
1 Using final to Prevent Overriding
While method overriding is one of Java’s most powerful features, there will be times when
you will want to prevent it from occurring. To disallow a method from being overridden,
specify final as a modifier at the start of its declaration. Methods declared as final cannot be
overridden. The following fragment illustrates final:
class A {
final void meth() {
[Link]("This is a final method."); }
}
class B extends A {
void meth() { // ERROR! Can't override. [Link]("Illegal!");
}
}

• Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do


so, a compile-time error will result.
• Methods declared as final can sometimes provide a performance enhancement: The
compiler is free to inline calls to them because it “knows” they will not be overridden
by a subclass.
• When a small final method is called, often the Java compiler can copy the bytecode
for the subroutine directly inline with the compiled code of the calling method, thus
eliminating the costly overhead associated with a method call.
[Link] final to Prevent Inheritance
Sometimes you will want 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 methods as
final, too. As you might expect, it is illegal to declare a class as both abstract and final since
an abstract class is incomplete by itself and relies upon its subclasses to provide complete
implementations.
Here is an example of a final class:
final class A { //...
}

21
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

// The following class is illegal. class B extends A { // ERROR! Can't subclass A //...
}

Local Variable Type Inference (var) and Inheritance


Local Variable Type Inference is a Java 10 feature that allows declaring local variables using
the keyword var. The compiler automatically infers the datatype based on the right-side
value. It reduces code length and increases readability.
It can be used only for:
• local variables,
• loops,
• blocks inside methods.
The variable must be initialized at the time of declaration.
Syntax:
var varName = value;
Example:
var x = 10; // int
var name = "Ram"; // String
Local Variable Type Inference with Inheritance
When using var to store objects of subclass types, the inferred datatype is the subclass itself.
Method overriding and dynamic dispatch still work normally.
Program Demonstrating var + Inheritance
class Animal {
var name =”papi”; //String
var age =20; //int
void sound() {
[Link]("Animals make sounds");
}
}
class Dog extends Animal {

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

THE OBJECT CLASS


Java provides a special class called Object in the [Link] package. All classes in Java
implicitly extend Object, making it the root of the class hierarchy. Because of this, every Java
object inherits common methods such as toString(), equals(), hashCode(), clone(), and
others.
A reference variable of type Object can refer to any class object. Arrays are also treated as
objects, therefore they can also be assigned to an Object reference.

Method Purpose

Object clone() Creates a copy of the object.

boolean equals(Object obj) Compares two objects for equality.

23
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

Method Purpose

Called before object is destroyed (Deprecated in


void finalize()
JDK 9).

Class<?> getClass() Returns the runtime class of the object.

int hashCode() Returns hash code (unique integer representation).

void notify() Wakes up a single thread waiting on the object.

void notifyAll() Wakes up all waiting threads.

String toString() Returns string description of the object.

void wait() Causes current thread to wait.

void wait(long ms) Waits for specified time.

void wait(long ms, int ns) Waits for specified ms + ns.

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) {

Student s1 = new Student(1, "Amit");


Student s2 = new Student(1, "Amit");
[Link]([Link]()); // Calls toString()
[Link]([Link](s2)); // Calls equals()
[Link]([Link]()); // Shows runtime class
[Link]([Link]()); // Unique hash value
}
}
Output
Roll: 1, Name: Amit
true
class Student
213456789 (example hash value)

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 {

// public + abstract methods (by default)

void method1();

void method2();

Example

interface Animal {

void sound(); // abstract method

void eat();

class Dog implements Animal {

public void sound() {

[Link]("Dog barks");

public void eat() {

[Link]("Dog eats bones");

class Demo {

public static void main(String args[]) {

Animal a = new Dog();

[Link]();

[Link]();

26
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

Output

Dog barks

Dog eats bones

Important Points About Interfaces

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

Multiple Inheritance Using Interfaces

interface A {

void show();

interface B {

void display();

class C implements A, B {

public void show() {

[Link]("From A");

public void display() {

[Link]("From B");

27
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

class Demo {

public static void main(String[] args) {

C obj = new C();

[Link]();

[Link]();

Interface Features After Java 8

Interfaces can now contain:

Default Methods (with body)

interface Test {

default void hello() {

[Link]("Hello from default method!");

Static Methods

interface Test {

static void show() {

[Link]("Static method in interface");

Private Methods (Java 9+)

Used inside interface only.

28
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

Example

interface PaymentGateway {

void pay(int amount);

class GooglePay implements PaymentGateway {

public void pay(int amount) {

[Link]("Paid ₹" + amount + " using GooglePay");

class PhonePe implements PaymentGateway {

public void pay(int amount) {

[Link]("Paid ₹" + amount + " using PhonePe");

class Demo{

public static void main(String[] args) {

PaymentGateway p = new GooglePay();

[Link](500);

29
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

Comparison: Interface vs Abstract Class

Points Abstract Class Interface

Cannot be instantiated; contains


Specifies a set of methods a
both abstract (without
class must implement; methods
implementation) and concrete
are abstract by default.
Definition methods (with implementation)

Methods are abstract by


Can have both implemented and
Implementation default; Java 8, can have
abstract methods.
Method default and static methods.

class can inherit from only one A class can implement


Inheritance abstract class. multiple interfaces.

Methods and properties can have


Methods and properties are
any access modifier (public,
implicitly public.
Access Modifiers protected, private).

Can have member variables


Variables are implicitly public,
(final, non-final, static, non-
static, and final (constants).
Variables static).

Default Method in an Interface


Before Java 8, interfaces in Java could only have abstract methods (methods without a body).
The implementation of these methods has to be provided in a separate class. Java 8
introduced default methods in interfaces, allowing methods with a body (implementation).
This makes interfaces more flexible and backward-compatible.

Key Features

1. Interfaces can now have both abstract and default methods.

2. Default methods provide backward compatibility without breaking existing code.

3. They allow API evolution and support new features like Streams and Lambdas.

30
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

Example : Default Method in an Interface

interface TestInterface {

// abstract method

public void square(int a);

// default method

default void show()

[Link]("Default Method Executed");

class TestClass implements TestInterface

{ // implementation of square abstract method

public void square(int a)

[Link](a*a);

public static void main(String args[])

TestClass d = new TestClass();

[Link](4);

// default method executed

[Link]();

31
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

Use static Methods in an Interface


A static method in an interface is a method that belongs to the interface itself and not to the
objects of the implementing classes. It can be called using the interface name and cannot be
overridden in the implementing classes. (Introduced in Java 8)

Key Features

1. Declared with the static keyword inside an interface.

2. Contain a complete definition and cannot be overridden.

3. Called using the interface name only (e.g., [Link]()).

4. The scope of the static method is limited to the interface in which it is defined.

Syntax

interface InterfaceName {

static void methodName() {

// method body

Example

interface NewInterface {

// static method

static void hello()

[Link]("Hello, New Static Method Here");

// Public and abstract method of Interface

void overrideMethod(String str);

32
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

// Implementation Class

public class InterfaceDemo implements NewInterface {

public static void main(String[] args)

InterfaceDemo interfaceDemo = new InterfaceDemo();

// Calling the static method of interface

[Link]();

// Calling the abstract method of interface

[Link]("Hello, Override Method here");

// Implementing interface method

@Override

public void overrideMethod(String str)

[Link](str);

Output

Hello, New Static Method Here

Hello, Override Method here

Private methods in an interface


Private methods in an interface are methods that are used only inside the interface to support
default methods or static methods. They cannot be accessed or overridden by implementing
classes. (Introduced in Java 9)

33
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

Using private methods in interfaces have four rules :

1. Private interface method cannot be abstract.


2. Private method can be used only inside interface.
3. Private static method can be used inside other static and non-static interface methods.
4. Private non-static methods cannot be used inside private static methods.

Types of Private Methods

[Link] Instance Method

private void helper() { … }

[Link] Static Method

private static void util() { … }

Eg:

interface Demo {

// ----- Private Instance Method -----

private void instanceHelper() {

[Link]("Private instance method");

// ----- Private Static Method -----

private static void staticHelper() {

[Link]("Private static method");

// ----- Default Method (Can call private instance method) -----

default void show() {

instanceHelper(); // allowed

34
DEPT. OF CSE-DS,KNSIT
OOPS WITH JAVA BCS306A

// ----- Static Method (Can call private static method) -----

static void display() {

staticHelper(); // allowed

// Implementing class

class TestDemo implements Demo {

// No need to override anything

public class Main {

public static void main(String[] args) {

TestDemo obj = new TestDemo();

// calling default method using object

[Link]();

// calling static method using interface name

[Link]();

OUTPUT

Private instance method

Private static method

35
DEPT. OF CSE-DS,KNSIT

You might also like