0% found this document useful (0 votes)
12 views72 pages

Java Object-Oriented Programming Concepts

The document outlines the syllabus for an Object Oriented Programming course with a focus on Java, taught by Arun K H at Acharya Institute of Technology. It covers key concepts such as inheritance, method overriding, dynamic method dispatch, and types of inheritance, along with examples and explanations. The document also includes references to textbooks and provides insights into constructor execution and the use of the 'super' keyword.

Uploaded by

babysharkchatgpt
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)
12 views72 pages

Java Object-Oriented Programming Concepts

The document outlines the syllabus for an Object Oriented Programming course with a focus on Java, taught by Arun K H at Acharya Institute of Technology. It covers key concepts such as inheritance, method overriding, dynamic method dispatch, and types of inheritance, along with examples and explanations. The document also includes references to textbooks and provides insights into constructor execution and the use of the 'super' keyword.

Uploaded by

babysharkchatgpt
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

Dept.

of ISE

Object Oriented Programming with JAVA


Subject Code: BCS306A
Who am I?

ARUN K H
Assistant Professor,
Department of ISE,
Appian Certified Associate Developer,
Dept. of ISE Appian Authorized Instructor,
Acharya Institute of Technology,
18+ Years of Experience
Syllabus Overview
Module–3

Chapter 8: Inheritance Chapter 9: Interfaces

● Inheritance Basics ● Interfaces

● Using super ● Default Interface Methods

● Creating a Multilevel Hierarchy ● Use static Methods in an Interface


Dept. of ISE ● When Constructors Are Executed ● Private Interface Methods.

● Method Overriding
● Dynamic Method Dispatch
● Using Abstract Classes
● Using final with Inheritance
● Local Variable Type Inference and
Inheritance
● The Object Class.
Syllabus Overview
Text Books

● Java: The Complete Reference, Twelfth Edition, by Herbert Schildt, November 2021,
McGraw-Hill, ISBN: 9781260463422

Reference Books
Dept. of ISE
● Programming with Java, 6th Edition, by E Balagurusamy, Mar-2019, McGraw Hill
Education, ISBN: 9789353162337.
● Thinking in Java, Fourth Edition, by Bruce Eckel, Prentice Hall, 2006
([Link]
Module 3
Dept. of ISE

Chapter 8
Inheritance Basics
● Inheritance is one of the core concepts of object-oriented programming
(OOP) in Java.
● It allows a new class (subclass) to inherit properties and behavior (fields
and methods) from an existing class (superclass), promoting code reuse,
extensibility, and maintainability.

Dept. of ISE ● Inheritance forms an "is-a" relationship between classes, where the child
class is a type of the parent class.
Key Points
● The class that is inherited from is called the superclass or parent class or
base class.
● The class that inherits is called the subclass or child class or derived class.
● The extends keyword is used to inherit a class.
Example
class Animal { public class Main {
void eat() { public static void main(String[] args) {
[Link]("This animal eats food."); Animal a=new Animal();
} [Link]();
} Dog d = new Dog();
// Dog class inherits Animal class [Link](); // Inherited from Animal class

Dept. of ISE class Dog extends Animal { [Link](); // Method of Dog class
void bark() { }
[Link]("The dog barks."); }
}
} Output
This animal eats food.
This animal eats food.
The dog barks.
Method Overriding in Java
● Method overriding is a feature in object-oriented programming that allows a
subclass to provide a specific implementation for a method that is already
defined in its superclass.
● When a method is overridden, the method in the subclass has the same signature
(name, return type, and parameters) as the method in the superclass, but the
implementation in the subclass is different.
Dept. of ISE
Key Features of Method Overriding:
● Same Method Signature:
○ The method in the subclass must have the same name, return type (or a
subtype), and parameter list as the method in the superclass.
● Inheritance:
○ Method overriding can only occur when a subclass inherits a method from a
superclass.
Method Overriding in Java
● Run-time Polymorphism:
○ Method overriding is a key part of achieving runtime polymorphism in Java.
○ This allows Java to determine at runtime which method to call, based on the
object that is referenced.
● Access Modifier Rules:
○ The overridden method in the subclass must not have a more restrictive
Dept. of ISE
access modifier than the method in the superclass.
○ For example, if the superclass method is public, the overriding method must
also be public or more accessible.
● Use of super:
○ The super keyword can be used within the subclass to call the superclass's
version of the overridden method.
Example
/class Animal { public class Main {
// Method to be overridden public static void main(String[] args) {
public void sound() {
Animal myAnimal = new Animal();
[Link]("Animal makes a sound");
Dog myDog = new Dog();
}
}
Cat myCat = new Cat();
class Dog extends Animal {
// Overriding the sound() method in Animal class [Link]();
public void sound() { [Link]();
Dept. of ISE [Link]("Dog barks"); [Link]();
}
}
}
}
class Cat extends Animal {
// Overriding the sound() method in Animal class
public void sound() { Output
[Link]("Cat meows"); Animal makes a sound
Dog barks
}
Cat meows
}
Dynamic Method Dispatch in java
● Dynamic Method Dispatch, also known as runtime polymorphism or late
binding, is a mechanism in Java that allows method calls to be resolved
at runtime rather than compile-time.
● This feature is achieved by using a superclass reference to refer to a
subclass object, enabling the Java Virtual Machine (JVM) to decide
Dept. of ISE which method implementation (from the superclass or subclass) to
invoke based on the actual object type.
Key Concepts of Dynamic Method Dispatch
Method Overriding:
● Dynamic method dispatch relies on method overriding, where a subclass
provides a specific implementation of a method that is already defined in
its superclass.
Dynamic Method Dispatch in java
Superclass Reference and Subclass Object:
● In Java, a reference variable of a superclass type can hold a reference to
an object of any subclass of that superclass.
Runtime Decision:
● At runtime, Java uses the actual type of the object (not the type of the
Dept. of ISE reference) to determine which overridden method to call. This is the
essence of dynamic method dispatch.
Example for Dynamic Method Dispatch in java
class Animal {
void sound() { public class Main {
[Link]("This is a generic animal public static void main(String[] args) {
sound."); // Superclass reference pointing to a subclass object
} Animal a;
}
class Dog extends Animal { // Dynamic dispatch to Dog's sound method
void sound() { a = new Dog();
[Link]("Dog barks."); [Link](); // Output: Dog barks.
Dept. of ISE
}
} // Dynamic dispatch to Cat's sound method
class Cat extends Animal { a = new Cat();
void sound() { [Link](); // Output: Cat meows.
[Link]("Cat meows."); }
} }
}
Output
Dog barks.
Cat meows.
Inheritance Types
● Java supports several types of inheritance, though with some restrictions like
the absence of multiple inheritance using classes.
● Types of inheritance
○ Single Inheritance
○ Multilevel Inheritance

Dept. of ISE ○ Hierarchical Inheritance


○ Multiple Inheritance (Not supported with classes, only through
interfaces)
○ Hybrid Inheritance (Not directly supported)
Inheritance Types

Dept. of ISE

Hierarchical Inheritance
Single Inheritance
● In single inheritance, a class (subclass) inherits from one superclass.
● This is the most basic form of inheritance and establishes a simple
parent-child relationship between two classes.
Key Points:
● The subclass inherits fields and methods from the superclass.
Dept. of ISE ● Java allows a subclass to override methods from the superclass to
provide specific functionality.
Single Inheritance Example
class Animal { public class Main {
void eat() { public static void main(String[] args) {
[Link]("This animal eats food."); Dog d = new Dog();
} [Link](); // Inherited method
} [Link](); // Dog's own method
// Dog inherits from Animal }

Dept. of ISE class Dog extends Animal { }


void bark() {
[Link]("The dog barks.");
Output
} This animal eats food.
The dog barks.
}
Multilevel Inheritance
● In multilevel inheritance, a class (child) inherits from another class
(parent), and that class (parent) in turn inherits from another class
(grandparent), forming a hierarchy of inheritance.
● This establishes a chain of inheritance across multiple levels.
Key Points:
Dept. of ISE ● Each class inherits from its immediate superclass.
● The child class inherits properties from all classes above it in the
hierarchy.
Multilevel Inheritance Example
class Animal { public class Main {
void eat() { public static void main(String[] args) {
[Link]("This animal eats food."); Puppy p = new Puppy();
} [Link](); // Inherited from Animal class
} [Link](); // Inherited from Dog class
class Dog extends Animal {
[Link](); // Method of Puppy class
void bark() {
Dept. of ISE }
[Link]("The dog barks.");
}
}
} Output
This animal eats food.
class Puppy extends Dog {
The dog barks.
void weep() { The puppy weeps.
[Link]("The puppy weeps.");
}
}
Hierarchical Inheritance
● In hierarchical inheritance, multiple subclasses inherit from the same
superclass.
● This is useful when you want to create different types of objects that
share common behavior (from the superclass), but also have distinct
properties and behaviors.
Dept. of ISE Key Points:
● One superclass has multiple subclasses.
● Each subclass inherits the properties and behavior of the common
superclass but can have its own unique behavior.
Hierarchical Inheritance Example
class Animal { public class Main {
void eat() { public static void main(String[] args) {
[Link]("This animal eats food."); Dog d = new Dog();
} Cat c = new Cat();
} [Link]();
class Dog extends Animal {
[Link]();
void bark() {
Dept. of ISE [Link]();
[Link]("The dog barks.");
[Link]();
}
}
}
}
class Cat extends Animal {
void meow() { Output
[Link]("The cat meows."); This animal eats food.
The dog barks.
} This animal eats food.
} The cat meows.
Multiple Inheritance (Not supported with classes, only through interfaces)
● Java does not support multiple inheritance with classes due to the
"diamond problem", where ambiguity arises if two parent classes define
a method with the same signature and the subclass does not know which
method to inherit.
● However, Java does support multiple inheritance using interfaces.
Dept. of ISE ● Multiple inheritance through interfaces: A class can implement multiple
interfaces, thereby inheriting behavior from multiple sources.
Key Points:
● A class can implement multiple interfaces.
● There is no ambiguity because interfaces only define method signatures
(no actual implementation).
Hybrid Inheritance (Not directly supported)
● Hybrid inheritance is a combination of two or more types of inheritance.
● Since Java does not support multiple inheritance with classes, hybrid
inheritance (a combination of hierarchical and multiple inheritance) is
not directly possible.
● However, you can achieve it indirectly using interfaces.
Dept. of ISE Key Points:
● It combines different forms of inheritance, but due to the limitation of no
multiple inheritance with classes, interfaces are often used to simulate
hybrid inheritance.
When Constructors Are Executed in inheritance?
In Java, constructors play a vital role in the instantiation of objects, especially
when inheritance is involved. Here's an in-depth look at when constructors are
executed in Java inheritance:
1. Constructor Execution Order in Inheritance
● When a subclass is instantiated in Java, a specific sequence determines the

Dept. of ISE order in which constructors are called:


○ Superclass Constructor First: The constructor of the superclass is
executed before the constructor of the subclass.
○ Subclass Constructor Next: Only after the superclass constructor
completes execution does the subclass constructor get invoked.
● This order ensures that the subclass has access to the initialized fields and
methods of the superclass.
Example for Constructor Execution Order in Inheritance
class SuperClass {
SuperClass( ) {
[Link]("Superclass constructor executed");
}
}
class SubClass extends SuperClass {
SubClass( ) {
Dept. of ISE [Link]("Subclass constructor executed");
}
}
public class Main {
public static void main(String[] args) {
SubClass sub = new SubClass();
Output:
}
// Superclass constructor executed
} // Subclass constructor executed
super() Keyword and Implicit Calls
● Implicit super() Call: Java automatically calls the no-argument constructor
of the superclass if no explicit constructor call is provided in the subclass.
● Explicit super() Call: You can explicitly call a superclass constructor with
specific parameters by using super(arguments); as the first statement in the
subclass constructor.

Dept. of ISE
Example for Explicit super() Call:
class SuperClass {
SuperClass(int x) {
[Link]("Superclass constructor with value: " + x);
}
}
class SubClass extends SuperClass {
SubClass(int y) {
super(y); // Explicit call to superclass constructor
[Link]("Subclass constructor with value: " + y);
Dept. of ISE }
}
public class Main {
public static void main(String[] args) {
SubClass sub = new SubClass(5);
}
}

Output:
Superclass constructor with value: 5
Subclass constructor with value: 5
Using super in Java
● The super keyword refers to the immediate parent class of an object. It is
commonly used in two scenarios:
○ Accessing Parent Class Members: When there is a conflict between
the parent and child class variables or methods (for example, if both
have variables with the same name).

Dept. of ISE ○ Calling Parent Class Constructor: A child class constructor can
invoke the parent class constructor using super().
Key Points:
● super can be used to refer to the immediate parent class's methods and
variables.
● super() is used to call the constructor of the parent class.
● super() must be the first statement in a subclass constructor.
Example
class Animal { public class Main {
String color = "Brown"; public static void main(String[] args) {
} Dog d = new Dog();
class Dog extends Animal { [Link]();
String color = "Black"; }
// same name as parent variable
}
void printColor() {
Dept. of ISE
[Link]("Dog's color: " + color);
// refers to Dog's color
[Link]("Animal's color: " + Output
[Link]);
Dog's color: Black
Animal's color: Brown
// refers to Animal's color using super
}
}
Here, [Link] is used to differentiate between the color field in the Dog and Animal classes.
Example of super() to Call Parent Class Constructor:
class Animal { public class Main {
Animal() { public static void main(String[] args) {
[Link]("Animal constructor is Dog d = new Dog();
called."); }
} }
}

Dept. of ISE
class Dog extends Animal {
Dog() {
super(); // calls the constructor of Animal Output
[Link]("Dog constructor is called."); Animal constructor is called.
Dog constructor is called.
}
}
final Keyword
● The final keyword in Java is a modifier used to apply restrictions on
variables, methods, and classes. It serves different purposes depending on
how it is used.
● The final keyword ensures that certain elements cannot be modified or

Dept. of ISE
overridden once they are defined.
There are three main uses of the final keyword:
● Final Variables: A constant value that cannot be changed.
● Final Methods: A method that cannot be overridden by subclasses.
● Final Classes: A class that cannot be subclassed (extended).
final Variables
● When a variable is declared as final, its value cannot be modified after it has
been initialized.
● Essentially, this makes it a constant.
● A final variable can be initialized only once, either at the time of declaration or
in the constructor.
Characteristics:
Dept. of ISE
● Once assigned, a final variable cannot be reassigned.
● Final variables are often used for constants.
● If the final variable is not initialized at the time of declaration, it is called a blank
final variable and must be initialized in the constructor.
final varibale example
class TestFinalVariable {
final int maxSpeed = 120; // final variable initialized at declaration

void display() {
maxSpeed = 150; // Error: cannot assign a value to final variable
[Link]("Max Speed: " + maxSpeed);
}
Dept. of ISE

public static void main(String[] args) {


TestFinalVariable obj = new TestFinalVariable();
[Link]();
}
}
final method
● When a method is declared as final, it cannot be overridden by subclasses.
● This is particularly useful when you want to prevent specific behavior in a class
from being modified by child classes.
Characteristics:
● A final method cannot be overridden, but it can be inherited.
● It ensures that the method's implementation remains unchanged in derived
Dept. of ISE
classes.
final method example
class Parent {
// Final method
final void show() {
[Link]("This is a final method in Parent class.");
}
}
class Child extends Parent {
// This will cause an error because final methods cannot be overridden
Dept. of ISE void show() {
[Link]("Trying to override final method.");
}
}
public class Main {
public static void main(String[] args) {
Child obj = new Child();
[Link](); // Calls the inherited final method from the Parent class
}
}
final class
● When a class is declared as final, it cannot be extended (inherited) by any other
class.
● This is useful when you want to prevent inheritance for security reasons, or
when the class's functionality is complete and should not be modified.
Characteristics:
● A final class cannot be subclassed.
Dept. of ISE
● All methods in a final class are implicitly final, since they cannot be overridden.
● Often used for classes like String, Integer, etc., which are immutable.
final class example
final class FinalClass {
void display() {
[Link]("This is a final class.");
}
}
//This will cause an error because final classes cannot be extended
class SubClass extends FinalClass {
Dept. of ISE
Error: cannot inherit from final class
}
public class Main {
public static void main(String[] args) {
FinalClass obj = new FinalClass();
[Link]();
}
}
Abstract Classes in Java
● In Java, abstract classes are used to define classes that cannot be instantiated but
can be subclassed.
● Abstract classes provide a template for other classes and are essential in
scenarios where you want to define a general concept with certain common
behavior but need specific implementations in subclasses.
Key Points on Abstract Classes in Java
Dept. of ISE
Definition and Syntax
● An abstract class is declared using the abstract keyword.
● Abstract classes cannot be instantiated, meaning you cannot create an object of
an abstract class directly.
Syntax: abstract class Animal {
abstract void sound();
}
Abstract Classes in Java
Purpose of Abstract Classes
● They provide a base class with common attributes and methods.
● Abstract classes allow you to define abstract methods (methods without a body)
that must be implemented by subclasses.
● They help enforce a standard for subclasses by defining abstract methods that
subclasses are required to implement.
Dept. of ISE
Abstract Methods
● An abstract method is declared without an implementation (no body).
● Subclasses must override and provide a specific implementation for each
abstract method.
Syntax abstract void sound(); // Abstract method in an abstract class
Abstract Classes in Java
Concrete Methods in Abstract Classes
● Abstract classes can also have concrete (non-abstract) methods with
implementations.
● This allows subclasses to inherit common functionality while requiring them to
implement only the abstract methods.
● Example
Dept. of ISE

abstract class Animal {


abstract void sound(); // Abstract method

void eat() { // Concrete method


[Link]("This animal eats food.");
}
}
Abstract Classes in Java
Usage of Abstract Classes in Inheritance
● Abstract classes are often used as a superclass in inheritance hierarchies.
● A subclass that extends an abstract class must either implement all abstract
methods or be declared abstract itself.
● Example:
class Dog extends Animal {
Dept. of ISE
void sound() {
[Link]("Dog barks");
}
}
Abstract Classes in Java
When to Use Abstract Classes
● Use abstract classes when you want to share code among closely related classes.
● Ideal when classes share some behavior but also need to enforce that some
methods must be implemented in subclasses.
● They are preferred when you need a class to define common behavior but should
not be instantiated on its own.
Dept. of ISE
Abstract class example
abstract class Animal { class Main {
// Abstract method (no body) public static void main(String[] args) {
abstract void sound(); Dog d = new Dog();
// Concrete method [Link](); // Outputs: Dog barks
void sleep() { [Link]();
[Link]("This animal is sleeping."); }
} }
Dept. of ISE
}
// Subclass (inherits from Animal)
class Dog extends Animal {
// Implement the abstract method
void sound() {
[Link]("Dog barks");
}
}
Abstract Classes in Java
Benefits of Abstract Classes
● Code Reusability: Common behaviors are defined once in the abstract class and
reused across subclasses.
● Polymorphism: Abstract classes support polymorphism, allowing for dynamic
method invocation.
● Extensibility: They provide a foundation for subclasses, making it easier to
Dept. of ISE
extend or modify functionality as needed.
Object classes in java
● In Java, the Object class is the parent class (or superclass) of all other classes.
● This means that every class in Java, either directly or indirectly, inherits from
Object.
● It’s part of the [Link] package, so it's automatically imported into every Java
program.
Key Points about the Object Class:
Dept. of ISE
● Inheritance: If a class doesn’t explicitly extend another class, it automatically
inherits from Object.
● Common Methods: The Object class defines several methods that all Java
classes inherit. These methods provide essential functionalities and can be
overridden to customize behavior.
Important Methods in the Object Class
● toString():
● equals(Object obj)
● hashCode()
● getClass()
● clone()
● finalize()
Dept. of ISE
● wait(), notify(), notifyAll()
Local Variable Type Inference and Inheritance
● In Java, Local Variable Type Inference (introduced in Java 10) and Inheritance
are powerful concepts that help make code more concise, flexible, and
adaptable.
Local Variable Type Inference
● Definition: Local Variable Type Inference allows Java to automatically infer the
type of a local variable based on the assigned value. It uses the var keyword.
Dept. of ISE
● Purpose: Simplifies code by reducing redundancy, especially when the type is
evident from the context.
● Syntax:
var variableName = value;
● Example
var name = "Java"; // Compiler infers this as a String
var number = 10; // Compiler infers this as an int
Rules and Limitations
● var can only be used for local variables (variables inside methods).
● Type inference is determined at compile-time, meaning var cannot be reassigned
to a value of a different type.
● Cannot use var for instance variables, return types, or method parameters.
● Improves readability when the type is obvious but can reduce clarity if overused.
Dept. of ISE
Inheritance and Type Inference:
● When using inheritance, if a subclass object is assigned to a var type, Java will
infer the type as the subclass type .
class Animal { }
Example: class Dog extends Animal { }
public class Example {
public static void main(String[] args) {
var a = new Dog(); // Compiler infers `a` as Dog type
}
}
Inheritance and Type Inference with var:
● When using var with inheritance, the inferred type is based on the right-hand
side of the assignment.
● If you want to treat ‘b’ as an Animal type (e.g., to call a superclass method),
you’d declare it as Animal explicitly. Otherwise, it remains as Dog.
● Example:
Dept. of ISE
Animal a = new Dog(); // Without var, explicit type Animal

var b = new Dog(); // b inferred as Dog, not Animal


class Animal {
void sound() {
[Link]("Animal sound");
}
}
class Dog extends Animal {
void sound() {
Dept. of ISE
[Link]("Dog barks");
}
}
Animal a = new Dog(); // Without var, explicit type Animal
var b = new Dog(); // b inferred as Dog, not Animal

Animal a = new Dog(); // Explicit Animal type allows polymorphism


var b = new Dog(); // Inferred as Dog, limiting polymorphic flexibility
When to Use var in Inheritance Scenarios
Use var when:
● The specific subclass type matters, and polymorphism isn’t needed.
● You want concise, readable code with obvious types.
Avoid var when:
● You want the flexibility of polymorphic behavior (using a superclass
Dept. of ISE type).
● It’s unclear what type the variable should hold at first glance.
Module 3
Chapter 9: Interfaces
● Interfaces
● Default Interface Methods
Dept. of ISE ● Use static Methods in an Interface
● Private Interface Methods.
Interfaces in Java
● Interface is way to achieve abstraction in Java.
● In Java, an interface is a reference type that allows you to define
abstract methods that any class implementing the interface must
provide implementations for.
● Interfaces are a key part of Java’s approach to abstraction and
Dept. of ISE polymorphism and allow for multiple inheritance of behavior, as
classes can implement multiple interfaces.
● The implements keyword is used to inherit/implement a interface.
Key Features of Interfaces in Java
Definition and Syntax
● An interface in Java is a blueprint of a class.
● An interface is defined using the interface keyword.
● Methods in an interface are implicitly abstract (i.e., they have no body)
and public unless specified otherwise.
Dept. of ISE ● All the fields are public, static and final by default.
● A class that implements an interface must implement all the methods
declared in the interface.
● Syntax: Example:
interface <interface_name>{
// declare constant fields interface Animal {
// declare methods as abstract int a;
} void eat();
}
Key Features of Interfaces in Java
interface Animal { interface Animal {
int a=15; public static final int a=15;
void sound(); public abstract void sound();
} }

Dept. of ISE
Implementing an Interface
● A class uses the implements keyword to implement an interface.
● The implementing class must provide concrete implementations for all
abstract methods in the interface.
● A class can implement multiple interfaces, allowing it to inherit behavior
from more than one source.
Dept. of ISE ● Example:

interface Animal { public void eat() {


void sound(); [Link]("Dog eats");
void eat(); }
} }
class Dog implements Animal {
public void sound() {
[Link]("Dog barks");
}
Relationship Between Class to Class
class Animal{
void eat(){
[Link]("Animal is eating");
}
}
class Dog extends Animal{
void sleep(){
[Link]("Dog is sleeping");
Dept. of ISE }
}
class Main{
public static void main(String args[]){
Dog d = new Dog();
[Link]();
[Link]();
}
}
Relationship Between Class and Interface
interface Animal{
void eat();
}
class Dog implements Animal{
void eat(){
[Link]("Dog is eating");
}
}
Dept. of ISE class Main{
public static void main(String args[]){
Dog d = new Dog();
[Link]();
}
}
Relationship Between Interface to Interface
interface Animal1{
void eat();
}
interface Animal2 extends Animal1{
void sleep();
}
class Dog implements Animal2{
void eat(){
[Link]("Dog is eating");
}
Dept. of ISE void sleep(){
[Link]("Dog is sleeping");
}
}
class Main{
public static void main(String args[]){
Dog a1=new Dog();
[Link]();
[Link]();
}
}
Implementing an multiple Interfaces
interface Animal1{
void eat();
}
interface Animal2{
void sleep();
}
class Dog implements Animal1, Animal2{
void eat(){
[Link]("Dog is
eating");
Dept. of ISE }
void sleep(){
[Link]("Dog is
sleeping");
}
}
class Main{
public static void main(String args[]){
Dog a1=new Dog();
[Link]();
[Link]();
}
}
extending an multiple Interfaces
class Dog implements Animal3{
void eat(){
[Link]("Dog is
eating");
}
void sleep(){
[Link]("Dog is
sleeping");
}
Dept. of ISE void sound(){
interface Animal1{ [Link]("Dog is
void eat(); barking");
} }
interface Animal2{ }
void sleep(); class Main{
} public static void main(String args[]){
interface Animal3 extends Animal1, Animal2{ Dog a1=new Dog();
void sound(); [Link]();
} [Link]();
[Link]();
}
}
Default Interface Methods in Java
● Java 8 introduced a significant enhancement to interfaces: Default
Interface Methods.
● This feature allows developers to add method implementations within
interfaces, which was not previously possible.
● Default methods enable backward compatibility and greater flexibility in
Dept. of ISE code design.
Overview of Default Interface Methods
● Definition: A default method is a method defined within an interface that
includes a body (implementation) using the default keyword.
● This new feature provides flexibility for adding methods to interfaces
without breaking the existing implementations of classes that use these
interfaces.
Default Interface Methods in Java
Syntax:
public interface MyInterface {
default void myMethod() {
[Link]("This is a default method");
}
}
Motivation Behind Default Interface Methods
Dept. of ISE
● Backward Compatibility: In earlier Java versions, adding new methods to an interface would
break the existing code that implemented it. Default methods allow new functionality to be
added without forcing existing classes to implement the new methods.
● Default methods are declared using the default keyword within an interface.
● They must include an implementation, and the body is similar to a regular
method in a class.
● Example:
public interface Vehicle {
default void start() {
[Link]("Starting the vehicle");
Dept. of ISE }
}
public class Car implements Vehicle {
// Inherits the default method 'start' from Vehicle
}
public class Bike implements Vehicle {
public void start() {
[Link]("Starting the bike");
}
}
Static Methods in Interfaces in Java
● Starting with Java 8, static methods were introduced in interfaces, along
with default methods.
● While interfaces traditionally only defined method signatures (abstract
methods), static methods allow developers to define utility methods
directly within interfaces.
Dept. of ISE Overview of Static Methods in Interfaces
● Definition: A static method in an interface is a method with an
implementation defined using the static keyword. It can be directly
invoked on the interface itself, without needing an instance of the
implementing class.
Static Methods in Interfaces in Java
Syntax:
public interface MyInterface {
static void myStaticMethod() {
[Link]("This is a static method in an interface.");
}
}
Dept. of ISE
Static methods in interfaces behave similarly to static methods in classes. However,
they are accessible through the interface name, not through an instance of an
implementing class.
Static Methods in Interfaces in Java
public interface MathOperations {
static int add(int a, int b) {
return a + b;
}
static int multiply(int a, int b) {
return a * b;
}
}
public class Calculator implements MathOperations {
Dept. of ISE // Calculator class can use the static methods directly from the interface
}
public class Main {
public static void main(String[] args) {
int sum = [Link](5, 3); // Calls static method add from MathOperations
int product = [Link](5, 3); // Calls static method multiply from MathOperations
[Link]("Sum: " + sum);
[Link]("Product: " + product);
}
}
Nested Interfaces in Java
● In Java, nested interfaces are interfaces declared within another interface
or class.
● This concept allows for better organization and encapsulation of related
interfaces, particularly when one interface or class serves as the logical
container for another.
Dept. of ISE ● Nested interfaces are often used to group interfaces that are closely
related or to simplify the external structure of a package by nesting
smaller interfaces within a primary interface or class.
Nested Interfaces in Java
Overview of Nested Interfaces
● Definition: A nested interface is an interface declared inside another interface or class. Nested
interfaces are defined just like regular interfaces, except they are nested within another
structure.
Types of Nesting:
● Interface within an Interface: Often used when a smaller interface is part of a larger interface
and will be implemented by classes implementing the outer interface.
Dept. of ISE
● Interface within a Class: Useful when the nested interface is logically tied to the enclosing
class, especially when used as a callback or to support class-specific functionality.
Nested Interfaces in Java
A nested interface can be declared within an interface or a class.
Example of Interface within an Interface:
public interface Vehicle {
void start();
// Nested interface
interface Engine {
void fuelType();
}
Dept. of ISE }
public class Car implements Vehicle, [Link] {
public void start() {
[Link]("Car starting...");
}
public void fuelType() {
[Link]("Petrol engine");
}
}
Nested Interfaces in Java
Example of Interface within a Class:
public class Computer {
// Nested interface
public interface Processor {
void process();
}
// Inner class implementing nested interface
public class IntelProcessor implements Processor {
public void process() {
Dept. of ISE [Link]("Intel processing...");
}
}
}
public class Main {
public static void main(String[] args) {
[Link] processor = new Computer().new IntelProcessor();
[Link]();
}
}
Dept. of ISE

You might also like