Java Main Notes Part5
Java Main Notes Part5
Inheritance In Java:
● In real life, inheritance means passing traits, properties, or wealth from parents to
children.
Example:
Similarly, in programming, one class can inherit properties and behaviors from another
class.
● In Java, inheritance is a mechanism that allows one class to inherit the properties and
behavior of another class. Just like how a child inherits certain physical traits and
characteristics from its parents, a child class in Java inherits certain properties and
behavior from its parent class. This allows you to reuse code and create more efficient
and organized class hierarchies.
● The superclass holds the code that the subclass reuses and modifies as needed. This
relationship is often described as the subclass inheriting from the superclass. The
superclass is alternatively called a base class or parent class, while the subclass may be
referred to as a derived class or child class.
● To understand inheritance, let's assume that you are trying to build Java classes
representing various superheroes from marvel universe like shown below.
● If you see, there is a lot of duplicate code representing their name, age, how they eat,
walk, sleep, and use power using variables & methods. The only method that may have
a different implementation for each hero is how they use their power.
● To avoid duplicating the same code across multiple classes, you can create a parent
class called Person that contains the shared properties and methods, and then inherit
from that class to create subclasses for each superhero with their unique power
implementation.
● Super class/Base class/Parent class: A class from which another class is derived.
● Subclass/Derived class/Child class: A class that is derived from a superclass.
Example:
● Car is a Vehicle
● Orange is a Fruit
● Surgeon is a Doctor
● Dog is an Animal
Syntax of Inheritance:
Example1:
//parent class
class Animal {
// methods and fields
}
//child class
class Dog extends Animal {
// methods and fields of Animal are inherited
}
Example2:
[Link]:
[Link]:
// child class inherits from parent// [Link]
//Dog is an Animal
class Dog extends Animal {
[Link]:
class Demo {
Types of Inheritance:
● In Java, multiple and hybrid inheritance can be achieved using the Interface concept.
We will learn about an interface later.
1. Single Inheritance
Example:
class Animal{
void eat(){
[Link]("eating...");
}
}
void bark(){
[Link]("barking...");
}
}
class Demo{
2. Multilevel Inheritance
● When there is a chain of inheritance, it is known as multilevel inheritance.
Example:
class Animal{
void eat(){
[Link]("eating...");
}
}
void bark(){
[Link]("barking...");
}
}
void weep(){
[Link]("weeping...");
}
}
class Demo{
3. Hierarchical Inheritance:
Animal
/ \
Dog Cat
Example:
class Animal{
void eat(){
[Link]("eating...");
}
}
void bark(){
[Link]("barking...");
}
}
void meow(){
[Link]("meowing...");
}
}
class Demo{
public static void main(String args[]){
● To reduce the complexity and simplify the language, multiple inheritance is not supported
in Java.
● Consider a scenario where A, B, and C are three classes. The C class inherits the A and
B classes. If A and B classes have the same method and you call it from a child class
object, there will be ambiguity in calling the method of the A or B class.
A
/ \
B C
\ /
D
Example:
class A{
void msg(){
[Link]("Hello");
}
}
class B{
void msg(){
[Link]("Welcome");
}
}
● In Java, a subclass does not inherit all aspects of its superclass. Instead, it selectively
inherits the following:
Inherited:
● Public members
● Protected members
● Static members
Not Inherited:
● Private members
● Constructors
● Static blocks
● Instance blocks
[Link]:
package [Link];
public class X {
int i = 10;
void funX() {
[Link]("inside funX() of X");
}
}
[Link]
package [Link];
public class Y extends X {
int j = 20;
void funY() {
[Link]("inside funY() of y");
}
public static void main(String[] args) {
Y y1=new Y();
[Link](y1.j);//Access subclass member
[Link](y1.i); //Access inherited member
[Link]();
[Link]();
}
}
Key Points:
○ If a class does not explicitly extend another class, it implicitly extends the
Object class.
○ The object of the superclass is created first, followed by the object of the
subclass.
[Link]:
package [Link];
public class X {
public X() {
[Link]("Inside the constructor of X class");
}
[Link]:
package [Link];
public class Y extends X {
public Y() {
[Link]("Inside the constructor of Y class");
}
Y y1 = new Y();
}
}
Output:
Example:
class Person {
// Code for the Person class
}
And
Important Notes:
● The Object class provides several important methods that are inherited by all
classes in Java:
○ Causes the current thread to wait until another thread invokes notify()
or notifyAll().
○ Causes the current thread to wait for a specified amount of time or until
notify()/notifyAll() is called.
○ Causes the current thread to wait for a specified amount of time (with
nanosecond precision) or until notify()/notifyAll() is called.
● In Java, polymorphism refers to the ability to perform a single action in multiple ways.
The term "polymorphism" is derived from the Greek words "poly" and "morphs", where
"poly" means many and "morphs" means forms, hence it means "many forms".
● In real life, we also see many examples of polymorphism. For instance, a woman can
play multiple roles in a day, like a mother, a wife, an employee, and a sister. So the same
person possesses different behavior in different situations. Polymorphism is considered
one of the important features of Object-Oriented Programming.
● Similarly, in programming:
● Based on the type of binding, there are two types of polymorphism in Java:
Achieved using:
● Method Overloading
Achieved using:
● Method Overriding
● Dynamic polymorphism
Method Overriding
● As we know, an object of a child class can also access the method of its parent class
also. But, if the child class object does not satisfy with the implementation of the
inherited method, the child class can re-implement the inherited method with its own
implementation; this concept is known as Method Overriding in Java.
● If an overridden method is called inside the subclass methods, then the version defined
in the subclass will always be called, and to access the version of super class in the
subclass methods, we have to use the super keyword.
● When overriding a method in the subclass, use the @Override annotation with the
method signature so that the compiler will check if the method signature in super class
and subclass is the same or not. If not the same, then the compiler will report an error.
Example:
[Link]:
package [Link];
class A{
void show(){
[Link]("Inside show of class A");
}
[Link]:
package [Link];
class B extends A{
@Override
void show(){ //class B has overridden the show method of class A
[Link]("Inside show of class B");
}
void fun(){
show();
[Link]();
}
A a = new A();
[Link]();
[Link]("-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=");
B b = new B();
[Link]();
[Link]("-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=");
[Link]();
}
}
Output:
○ The overriding method in the child class must have the same name as the
method in the parent class.
○ The parameter list (number, type, and order of parameters) must match exactly
with the method in the parent class.
2. Inheritance:
○ The child class must inherit from the parent class, establishing an IS-A
relationship.
○ The access modifier of the overriding method cannot be more restrictive than the
method in the parent class. For example:
○ The return type of the overriding method must be the same or a subtype
(covariant return type) of the return type declared in the parent class.
○ A static method belongs to the class, not the instance, so it is not subject to
overriding but can be hidden.
○ The overriding method cannot throw checked exceptions that are broader than
those declared in the parent method.
7. Annotation:
○ It is a good practice to use the @Override annotation to ensure that the method
is correctly overriding a superclass method.
● The super keyword in Java is used to refer to the immediate parent class's object.
○ The super keyword can be used to refer to the instance variables of the parent
class when they are hidden by subclass variables.
○ The super keyword can be used to invoke methods of the parent class if they
are overridden in the subclass.
class Animal{
String color="white";
}
String color="black";
void printColor(){
[Link](color);//prints color of Dog class
[Link]([Link]);//prints color of Animal class
}
}
class Demo{
class Animal{
void eat(){
[Link]("eating...");
}
}
@Override
void eat(){
[Link]("eating bread...");
}
void bark(){
[Link]("barking...");
}
void work(){
eat();
[Link]();
bark();
}
}
class Demo{
class Animal {
Animal(String name) {
[Link]("animal is created with name: " + name);
}
}
Dog(String name) {
super(name);
[Link]("dog is created with " + name);
}
}
class Demo {
public static void main(String args[]) {
Dog d = new Dog("Tommy");
}
}
Note: The super keyword and the this keyword can not be used inside the static area.
[Link]: Subclass
@Override
public double getOnRoadPrice() {
// Calculate the base on-road price and add the luxury tax
double baseOnRoadPrice = [Link]();
return baseOnRoadPrice + (getBasePrice() * luxuryTaxPercentage / 100.0);
}
}
[Link]:
// Regular vehicle
Vehicle car = new Vehicle(500000, 18.0); // Base price: 500,000, GST: 18%
[Link]("On-road price of the car: " + [Link]());
// Luxury vehicle
LuxuryVehicle luxuryCar = new LuxuryVehicle(1000000, 18.0, 10.0); // Base price:
1,000,000, GST: 18%, Luxury tax: 10%
● In Java, a parent class reference can point to the child class object.
● Generally, to any class reference variable, we can assign the following 3 things:
Example:
Parent p = null;
Upcasting:
● If the reference variable of the Parent class refers to the object of the Child class, it is
known as upcasting. For example:
Example:
class Bike{
void run(){
[Link]("running");
}
}
@Override
void run(){
[Link]("running safely for 60km");
}
public static void main(String args[]){
Output:
Explanation:
● In this example, we are creating two classes, Bike and Splendor. Splendor class extends
Bike class and overrides its run() method. We are calling the run method by the
reference variable of the Parent class. Since it refers to the subclass object and subclass
method overrides the Parent class method, the subclass method is invoked at runtime.
Since method invocation is determined by the JVM, not the compiler, it is known as
runtime polymorphism.
class Animal{
void eat(){
[Link]("eating");
}
}
void eat(){
[Link]("eating pedigree");
}
}
void eat(){
[Link]("drinking milk");
}
Output:
eating
eating pedigree
drinking milk
Golden Rule:
instanceof operator:
Example:
class Animal {
Note: An object of subclass type is also a type of parent class. For example, if Dog extends
Animal, then the object of Dog can be referred to by either the Dog or Animal class.
Example:
class Animal{
--
}
● As we know, to a parent class variable we can assign the child class object also, and
from that parent class variable, if we try to call any overridden method, then due to
Runtime polymorphism, the overridden method will be called. But if a parent class
reference points to a child class object, with that parent class reference, we can not call
the child class-specific methods, which are not available inside the parent class.
● To call the child class-specific method from the parent class reference variable, we need
to downcast the parent class variable to the appropriate child class object.
Example:
class Animal {
void eat() {
[Link]("eating...");
}
}
@Override
void eat() {
[Link]("eating bread...");
}
class Demo {
Note: We can downcast the parent class variable to the child class object only if the Parent
class variable points to the Child class object; Otherwise, it will throw a runtime exception called
ClassCastException.
Example:
class Animal {
void eat() {
[Link]("eating...");
}
}
@Override
void eat() {
[Link]("eating bread...");
}
class Demo {
void doSomething(Animal a) {
[Link]();
if (a instanceof Dog) {
Dog d = (Dog) a;
[Link]();
}
}
[Link](new Animal());
[Link](new Dog());
}
}
So:
Example:
class A {
int x = 10;
}
class B extends A {
int x = 20;
}
public class Demo {
public static void main(String[] args) {
A obj = new B();
[Link](obj.x);// 10
}
}
1. Variable
2. Method
3. Class
● If you make any variable final, you cannot change the value of a final variable(It will
become constant).
● In Java, the final variable must be initialized before we use it, either at the time of
declaration or inside the constructor of the class.
● If you make any method final, you cannot override it inside the child class.
● If you make any class a final, you cannot extend it. The final class does not have the
child class.
Initialization Rule
1. At declaration, OR
class Test {
final int x;
Test() {
}
● Important point:
Example:
class Parent {
Reason:
Example:
class Child extends FinalClass { // Compile-time error: cannot subclass final class
Example:
String
Math
Wrapper classes
Overriding the toString() method of the Object class:
Note: Whenever we try to print any Object reference, the toString() method is called internally.
● It is always recommended to override the toString() method to get our own String
representation of an object to show the meaningful object data.
Example:
package [Link];
class Student{
private int rollno;
private String name;
private String city;
Output:
[Link]@1fee6fc
[Link]@1eed786
● Let’s override the toString() method from the Object class in our Student class.
Example:
package [Link];
class Student {
[Link](s1);
[Link](s2);
}
}
Output:
● finalize() is a method of the Object class called before the object is garbage
collected.
● This method provides an opportunity for an object to release resources such as memory,
file handles, or network connections before it is destroyed.
Purpose
● Closing files
● Releasing resources
● Network cleanup
Method Syntax:
Key Points:
2. Purpose: It is mainly used for cleanup operations, such as releasing system resources
or closing network connections.
3. Override: You can override the finalize() method in your own classes to define
specific cleanup actions.
4. Garbage Collection: The finalize() method is not guaranteed to be called at any
specific time, and there’s no guarantee that it will be executed at all. It depends on the
garbage collector.
Example:
package [Link];
public class Demo {
void fun1() {
[Link]("inside fun1 of Demo class");
}
@Override
protected void finalize() throws Throwable {
[Link]("Cleanup operation is done");
[Link]("Object is destroyed by the GC");
}
● Here, we called the garbage collector explicitly by using [Link](); initiated the
memory cleanup process, otherwise the garbage collector is like a lazy person; if there is
sufficient memory, it may not destroy the object immediately.
● try-with-resources
In Summary:
Example:
class Vehicle {
Calling Methods:
Student Task:
Activity:
In this class:
1. Override the changeChannel() method so that the channel changes in a smart way.
Activity 2:
[Link]:
class Chef {
String name;
Chef(String name) {
[Link] = name;
[Link]("Chef " + name + " enters kitchen.");
}
void cookDish() {
[Link](name + " cooks normal food.");
}
}
void createSpecialDish() {
[Link](name + " creates a signature dish!");
}
● Inside the main method of the Demo class, create a MasterChef class object by
supplying the name of the Chef, and store that object in the Chef class variable.
Packages in Java:
● A package in Java is a mechanism used to group related classes, interfaces, enums,
and annotations into a single logical unit.
Simply put:
1. Code Organization
● Packages organize large projects into logical units, making maintenance easier.
2. Encapsulation
3. Access Control
● Access modifiers can restrict class and member visibility across packages.
4. Namespacing
Example:
[Link]
[Link]
Default Package
● If no package is specified:
class Demo {
}
● The above class Demo goes into the default (unnamed) package.
○ Small programs
○ Testing
○ Temporary code
Package Purpose
[Link] Networking
Package Structure
Example package:
[Link]
Folder structure:
college/
staff/
cse/
Note: A Package is like a folder in a file directory. In Java, every package is a folder, but not
every folder is a package.
Rules
Example:
[Link]
[Link]
[Link]
Example:
[Link]
import [Link];
import [Link].*;
Note: The above import will just import classes only, NOT sub-packages.
Example:
○ String
○ Object
○ System
○ Math
double c = 2 * PI * radius;
Advantage
Disadvantage
User-Defined Packages
● User-defined packages are those that are developed by users in order to group related
classes, interfaces, and sub-packages.
● As a Java developer, we should keep our user-defined classes, interfaces, Enums, and
annotations always inside a package.
● To create a package, use the package keyword: It should be the first statement of any
Java application.
Example:
//[Link]
package mypack;
Note: If a class is inside any package, in order to compile and run that class from the terminal
(command prompt), we need to make use of the following command:
Sub-Packages
Example:
[Link]
[Link]
[Link]
[Link]
Example:
[Link]
package [Link];
public class Simple {
● To compile and run the above class using the command prompt:
javac -d . [Link]
java [Link]
2. default: The access level of a default modifier is only within the same package. It
cannot be accessed from outside the package. If you do not specify any access level, it
will be the default.
3. protected: It is similar to default. The access level of a protected modifier is within the
same package and outside the package through a child class. If you do not make the
child class, it cannot be accessed from outside the package.
4. public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package, or outside the package.
Note: An outer class can only be default or public, whereas class members can be public,
private, protected, or default.
The following table displays the access levels for the different modifiers in Java:
Example: Role of Private Constructor:
● If you make any class constructor private, you cannot create an instance of that class
from outside the class.
Example:
class A {
private A() {// private constructor
}
void msg() {
[Link]("Hello java");
}
}
● In this example, we have created two packages: pack and mypack. We are accessing
the A class from outside its package, since the A class is not public, so it cannot be
accessed from outside the package.
//save by [Link]
package pack;
class A{
void msg(){
[Link]("Hello");
}
}
//save by [Link]
package mypack;
import pack.*;
class B{
}
}
● In this example, we have created the two packages pack and mypack. The A class of
the pack package is public, so it can be accessed from outside the package. But the
msg method of this package is declared as protected, so it can be accessed from
outside the class only through inheritance.
//save by [Link]
package pack;
public class A{
//save by [Link]
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
}
}
● If you are overriding any method ( declared in a subclass) must not be more restrictive.
Example:
class A{
Abstraction in Java:
● Abstraction is one of the four main concepts of Object-Oriented Programming (OOP):
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction
Definition
● Abstraction means hiding internal implementation details and showing only the
necessary functionality to the user.
In simple words:
1. Hides Implementation Details: Abstraction hides the internal mechanisms and
only reveals the operations that are relevant to the user.
3. Enhances Security: By hiding data and restricting access to certain parts of
code, abstraction helps secure the system.
4. Improves Code Maintainability: Changes to the internal implementation do not
affect the user as long as the interface remains unchanged.
You can:
● Withdraw money
● Check balance
● Deposit money
This is an abstraction.
Example
[Link]
if (choice == 1) {
withdrawAmount();
} else if (choice == 2) {
depositAmount();
} else {
[Link]("Invalid choice");
}
}
[Link]
import [Link];
public class Demo {
[Link]("Enter choice:");
int choice = [Link]();
Account account = new Account();
[Link](choice);
}
}
● Since Abstraction is about hiding unnecessary details and showing only what is
necessary
○ The user of the Account class does not know or need to know how these
methods work internally.
○ This makes the Account class easy to use while keeping the internal workings
secure and hidden.
In short:
Private methods hide method implementation, while abstract classes and interfaces hide
class-level implementation details.
● In Java, you can create a class for which objects cannot be instantiated; its sole purpose
is to represent an abstract idea shared among objects of other classes. Such a class is
termed an abstract class. Conversely, a “concrete class" is one that is not abstract, and
instances of it can be created. Up until now, all the classes you've created have been
concrete classes.
Syntax:
● As the Subject class is marked as abstract, creating an object of this class is not
permitted, despite having a public constructor (that gets automatically added by the
compiler).
● However, you can declare a variable of an abstract class, similar to how you declare
variables for concrete classes.
Example:
Example:
○ Abstract classes can define variables and even have constructors. However, the
constructor is invoked only when a subclass object is created.
Object creation Can not be created directly using Can be created using the new
Feature Abstract Class Concrete Class
Methods Can have both abstract and Only concrete methods are
concrete methods. allowed.
final keyword Abstract class can not be final A concrete class can be final
● Abstract class constructors are not used to create objects directly, but they run when a
subclass object is created.
● Must be extended
● Cannot be final
● An abstract method:
Example:
Important Rule
Abstract methods:
● Cannot be private
● Cannot be final
● Cannot be static
Note: inside a concrete class, we can not have an abstract method. Only an Abstract class or
an Interface can have an abstract method.
○ Credit Card
○ UPI
○ Net Banking
[Link]
@Override
public void pay(double amount) {
[Link]("Paid " + amount + " using UPI.");
}
}
[Link]:
@Override
public void pay(double amount) {
[Link]("Paid " + amount + " using Credit Card.");
}
}
[Link]:
Output:
Note: Subclasses that extend an abstract class must provide an implementation for all the
abstract methods of the parent class, otherwise we need to mark the child class also as an
abstract class.
Real-World Scenario
● Ride booking applications like Uber or Ola provide multiple ride options:
○ Bike
○ Auto
○ Cab
○ Start ride
○ Calculate fare
○ End ride
Problem Statement
● A variable: double distance, which is initialized using the constructor inside the
Ride class
● The following methods:
2. BikeRide, AutoRide, and CabRide classes implement their own fare calculation.
3. A method void bookRide(Ride ride) of the Demo class performs booking using
abstraction.
Solution:
[Link]:
package [Link];
public abstract class Ride {
double distance;
Ride(double distance) {
[Link] = distance;
}
void startRide() {
[Link]("Ride started...");
}
void endRide() {
[Link]("Ride ended.");
}
}
[Link]
package [Link];
public class BikeRide extends Ride {
BikeRide(double distance) {
super(distance);
}
double calculateFare() {
return distance * 50;
}
}
[Link]
package [Link];
public class AutoRide extends Ride {
AutoRide(double distance) {
super(distance);
}
double calculateFare() {
return distance * 80;
}
}
[Link]
package [Link];
public class CabRide extends Ride {
CabRide(double distance) {
super(distance);
}
double calculateFare() {
return distance * 150;
}
}
[Link]:
package [Link];
public class Demo {
if (ride != null) {
[Link]();
double fare = [Link]();
[Link]("Total Fare: " + fare);
[Link]();
} else {
[Link]("Ride is null: please choose a proper ride");
}
}
public static void main(String[] args) {
[Link]();
Student Task:
1. Predict the output:
class A {
int x = 10;
}
class B extends A {
int x = 20;
}
public class Test {
public static void main(String[] args) {
A obj = new B();
[Link](obj.x);
}
}
Output?
A) 10
B) 20
C) Compile error
D) Runtime error
A) Bark
B) Animal
C) Compile error
D) Runtime error
Interface in Java:
● An interface in Java is like a contract or a blueprint that defines what a class must
do, but not how it does it.
● It contains abstract method declarations (without implementation) and constants that
classes must implement.
Simple Definition
Multiple Inheritance
Loose Coupling
○ Code depends on behavior, not implementation.
Standardization
Syntax:
interface InterfaceName {
// constants
// abstract methods
}
Example:
[Link]
interface Printer {
void print();
}
● We also save an interface with the .java extension. And once we compile this .java file, a
.class file is created by the Java compiler for the interface.
Note: The Java compiler adds public and abstract keywords before the methods defined
inside an interface. Moreover, it adds public, static, and final keywords before variables inside
an interface.
Example:
[Link]:
Implementing an Interface:
Rule:
● The class that implements an interface must override all the abstract methods defined
inside that interface, otherwise we need to mark that class as an abstract class.
Example:
[Link]:
[Link]
[Link]
Here also the rule of the super class reference and subclass object is applicable.
Example: Food Delivery
[Link]:
interface DeliveryService {
void deliver();
}
[Link]
[Link]
[Link]:
● To call that method, we can pass either an implementation object or the default value
null.
Example:
[Link]:
package [Link];
public interface Payment {
void pay();
}
[Link]
package [Link];
public class CardPayment implements Payment {
@Override
public void pay() {
[Link]("Payment done using Card.");
}
// Extra method
public void generateCardReceipt() {
[Link]("Card receipt generated.");
}
}
[Link]:
package [Link];
public class UPIPayment implements Payment {
@Override
public void pay() {
[Link]("Payment done using UPI.");
}
// Extra method
public void showUPIRewards() {
[Link]("UPI reward points credited.");
}
}
[Link]:
package [Link];
public class Demo {
void processPayment(Payment p) {
[Link]("------------------");
}
[Link](new CardPayment());
[Link](new UPIPayment());
}
}
● If a Java method return type is an interface, then that method can return either any of its
implementation objects or it can return null also.
Example:
[Link]:
package [Link];
[Link]:
package [Link];
public class TajHotel implements Hotel {
@Override
public void chickenBiryani() {
[Link]("ChickenBiryani from TajHotel");
}
@Override
public void masalaDosa() {
[Link]("Masala Dosa from TajHotel");
}
[Link]:
package [Link];
public class RoadSideHotel implements Hotel {
@Override
public void chickenBiryani() {
[Link]("ChickenBiryani from RoadSide Hotel");
}
@Override
public void masalaDosa() {
[Link]("ChickenBiryani from RoadSide Hotel");
}
}
[Link]:
package [Link];
public class Demo {
return hotel;
}
Hotel h = [Link](800);
if (h != null) {
[Link]();
[Link]();
if (h instanceof TajHotel) {
TajHotel taj = (TajHotel) h;
[Link]();
}
} else
[Link]("Amount should be greater than 200");
}
}
Multiple Inheritance Using Interface:
● Java does not support multiple inheritance with classes, but with the interface, we can
achieve multiple inheritance in Java.
● But supports:
class C implements A, B
● If a class implements multiple interfaces, then that need to override all the abstract
methods present inside those interfaces.
Example:
interface Camera {
void clickPhoto();
}
interface MusicPlayer {
void playMusic();
}
[Link]:
class Demo {
public static void main(String[] args) {
}
}
Interface Inheritance:
● A class implements an interface, but one interface extends another interface. Infact one
interface can extend multiple interfaces simultaneously.
Example:
Then, any class that implements the interface C has to override all the 7 methods belongs to all
the interfaces, otherwise that class needs to be marked as an abstract class.
Example:
interface Printable {
void print();
}
● The class that implements the Showable interface needs to override print() as well as the
show() method; otherwise, we need to mark that class as an abstract class.
Note: A Java class can simultaneously extend another class and implement an interface also.
Syntax:
Example:
[Link]:
String name;
Animal(String name) {
[Link] = name;
}
[Link]:
interface Pet {
void play();
}
[Link]:
Dog(String name) {
super(name);
}
@Override
void makeSound() {
[Link]("Bark");
}
@Override
public void play() {
[Link]("Dog playing");
}
}
[Link]:
● Abstract methods
● Constants
● If you added a new method to an existing interface, all implementing classes would
break because they must implement that new method.
Analogy:
● Now, all existing vehicle classes (Car, Bike, Truck) will break if we add a new method like
startGPS().
Syntax:
interface InterfaceName {
void abstractMethod();
[Link]:
interface Vehicle {
void start();
[Link]
[Link]
class Demo{
Output:
Car is starting…
Here:
● Still it works
[Link]
class Demo{
}
}
Output:
Important Rules
3. If a class implements two interfaces with the same default method, the class must
override it to remove ambiguity.
interface A {
default void show() {
[Link]("A");
}
}
interface B {
● Demo class must override the show() method to resolve the conflict.
Analogy:
Think of an interface as a company's rule book.
For example:
Syntax:
interface InterfaceName {
Example:
[Link]
interface Bank {
void withdraw();
[Link]:
[Link]:
class Demo {
public static void main(String[] args) {
○ Abstract methods
● But sometimes, default and static methods need common internal logic.
● To avoid repeating code inside the interface, Java 9 introduced private methods
inside interfaces.
With private methods: You write helper logic once and reuse it.
Analogy:
Syntax
interface InterfaceName {
Example:
[Link]
interface Payment {
default void makePayment() {
validatePayment();
[Link]("Payment processed.");
}
[Link]:
[Link]:
class Demo {
○ Has no methods
○ Has no variables
○ Is completely empty
○ Is used to “mark” a class
Simple Definition
● A marker interface is an empty interface used to indicate that a class has a special
property.
Analogy:
Similarly:
Example 1: [Link]
[Link]:
interface PremiumUser {
}
[Link]:
● But many differences between an abstract class and an interface are given below.
An Abstract class can have abstract An Interface can have only abstract
and non-abstract methods. methods. Since Java 8, it can have
default and static methods also.
An Abstract class can have final, An Interface has only static and final
non-final, static, and non-static variables.
variables.
An abstract class can extend another An interface can extend another Java
Java class and implement multiple interface only.
Java interfaces.
A Java abstract class can have class Members of a Java interface are public
members like private, protected, etc. by default.