Thursday, 25 September 2025

Unit 3 - CSE B

 

Java Inheritance  ( ‘IS-A’ relationship)

 

It is a mechanism in which one object acquires all the properties and behaviors of a parent object. 

 

Why use inheritance?

 

Terms used in Inheritance

  • Super Class/ Parent Class/Base Class: Superclass is the class from where a subclass inherits the features.
  • Sub Class/ Child Class / Derived Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.

 

Ex:-

Class A

{

 

}

Class B extends A

{

 

}

 

class A

{

                void hello()

                {

                                System.out.println("Hello");

                }

 

}

class B extends A

{

 

                void friend()

                {             

                                super.hello();

                                System.out.println("Friend");

                }

 

                public static void main(String a[])

                {

                                B b = new B();

                                b.friend();

                }

 

}

 

Output :

----------------

Hello

Friend

 

super:   The super keyword in Java is a reference variable used within a subclass to refer to the immediate parent class object.

extends: The extends keyword in Java is used to establish an inheritance relationship between two classes, where one class (the subclass or derived class) inherits properties and methods from another class

class Employee

{ 

                float salary=40000; 

} 

 

class Programmer extends Employee

{ 

                int bonus=10000; 

} 

 

class Main

{ 

                public static void main(String args[])

                { 

                                Programmer p=new Programmer(); 

                                System.out.println("Programmer salary is:"+p.salary); 

                                System.out.println("Bonus of Programmer is:"+p.bonus); 

                } 

} 

Types of Inheritance

·         Single Inheritance

·         Multilevel Inheritance

·         Hierarchical Inheritance

·         Multiple Inheritance

·         Hybrid Inheritance

 

Single Inheritance :



Class A

{

 

}

Class B extends A

{

 

}

 

 

·         Multilevel Inheritance



Class A

{

 

}

Class B extends A

{

 

}

Class C extends B

{

 

}

 

Hierarchical Inheritance



Class A

{

 

}

Class B extends A

{

 

}

Class C extends B

{

 

}

 

 

·         Multiple Inheritance



 

Class A

{

 

}

Class B

{

 

}

Class C extends A, B

{

 

}

·         Hybrid Inheritance : It’s a combination of Hierarchial & Multiple inheritance



 

1. Single Inheritance

🔹 One child class inherits from one parent class.

🔹 The child class can access properties and methods of the parent class.

Example:

// Parent Class

class Animal

{

void eat()

{            System.out.println("This animal eats food.");      }

}

 

// Child Class (Inheriting from Animal)

class Dog extends Animal

{

void bark()

{           System.out.println("Dog barks.");       }

}

 

public class SingleInheritance

{

public static void main(String[] args)

{

Dog myDog = new Dog();

myDog.eat(); // Inherited method

myDog.bark(); // Child class method

}

}

 

2. Multilevel Inheritance

🔹child class inherits from a parent class, and another class further inherits from the child class.

🔹 Forms a chain of inheritance.

Example:

// Grandparent Class

class Animal

{

void eat()

{           System.out.println("This animal eats food."); }

}

 

// Parent Class

class Mammal extends Animal

{

void walk()

{           System.out.println("Mammals can walk.");               }

}

 

// Child Class

class Dog extends Mammal

{

void bark()

{           System.out.println("Dog barks.");                   }

}

 

public class MultilevelInheritance

{

public static void main(String[] args)

{

Dog myDog = new Dog();

myDog.eat(); // Inherited from Animal

myDog.walk(); // Inherited from Mammal

myDog.bark(); // Own method

}

}

 

3. Hierarchical Inheritance

🔹 One parent class has multiple child classes.

🔹 Each child class inherits from the same parent.

Example:

// Parent Class

class Animal

{

void eat()

{           System.out.println("This animal eats food."); }

}

 

// Child Class 1

class Dog extends Animal

{

void bark()

{           System.out.println("Dog barks.");                   }

}

 

// Child Class 2

class Cat extends Animal

{

void meow()

{           System.out.println("Cat meows.");                 }

}

 

public class HierarchicalInheritance

{

public static void main(String[] args)

{

Dog myDog = new Dog();

myDog.eat();

myDog.bark();

Cat myCat = new Cat();

myCat.eat();

myCat.meow();

}

}

 

 

 

 

 

Overriding in Java

·          

·         Overriding in Java occurs when a child class implements a method that is already defined in the parent class.

·         The subclass method must match the parent class method's name, parameters, and return type.

 

 

Note:

·         Java picks which method to run, based on the actual object type, not just the variable type.

·         Static methods cannot be overridden.

·         The @Override annotation catches mistakes like typos in method names.

 

 

 

 

Imp points to remember

How do I stop inherit/override my methods in Java…..??

   Ans : Declare the method with static

How do I stop inherit my class in Java…..??

  Ans : Declare the class as “final”

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Abstract Class in Java

ü  In Java, an abstract class is a class that cannot be instantiated (i.e., you cannot create objects directly from it).

ü  It is declared using the abstract keyword and is meant to be extended by other classes.

ü  Abstract classes are used when you want to define a base class that provides common structure and behavior but leaves some methods for subclasses to implement.

 

 

Key Points about Abstract Class

1.     Declared using the keyword abstract.

2.     abstract class Animal { }

3.     Can contain:

o    Abstract methods (methods without body, only declaration).

o    Concrete methods (methods with implementation).

o    Constructors, fields, and static methods.

4.     Cannot be instantiated directly.

5.     Animal a = new Animal(); //  Not allowed

6.     Subclasses must provide implementations for all abstract methods, unless the subclass is also abstract.

7.     Supports inheritance (using extends).

8.     Can have final methods (which cannot be overridden).

9.     Can implement interfaces.


Syntax

abstract class ClassName 
{
           abstract void method1();      // Abstract method (no body)
 
           void method2()          // Concrete method
           {
                     System.out.println("This is a concrete method");
            }
}
 
Note : Abstract classes are 0-100% abstract.

An abstract class can be 0% to 100% abstract.

·         0% abstract → If it has no abstract methods, only concrete methods.

·         100% abstract → If it has only abstract methods (but still declared with abstract keyword).

·         Partial abstraction (1%–99%) → If it has a mix of abstract and concrete methods.

 
 
// Abstract class
abstract class Animal 
{
    
    abstract void sound();      // Abstract method (no body)
 
           void sleep()     // Concrete method
          {
               System.out.println("Sleeping...");
          }
}
 
// Subclass (inheriting from abstract class)
class Dog extends Animal 
{
    @Override
    void sound() 
    {
        System.out.println("Barks");
    }
}
 
class Main 
{
    public static void main(String[] args)
    {
        Animal myDog = new Dog();  // Allowed (Polymorphism)
        myDog.sound();  // Barks
        myDog.sleep();  // Sleeping...
    }
}

When to use Abstract Class

·         When you want to provide a base class with partial implementation.

·         When you want common fields or methods for multiple related classes.

·         When you need constructors or non-static variables (which interfaces do not allow).

 

 

Difference between Abstract Class and Concrete Class in Java

 

Feature

Abstract Class

Concrete Class

Definition

A class declared with the abstract keyword that cannot be instantiated directly.

A normal class with complete implementation that can be instantiated.

Object Creation

Cannot create objects directly.

Can create objects directly.

Methods

Can have abstract methods (without body) and concrete methods (with body).

Contains only concrete methods (all methods must have body).

Implementation

May provide partial implementation; subclasses must complete it.

Provides full implementation of all methods.

Inheritance

Must be extended by a subclass to provide complete behavior.

Can be extended, but already has complete behavior.

Use Case

Used as a base class to enforce a contract and share common functionality.

Used when you need a fully usable class with no pending implementation.

 

 

 

 


 

 

 

 

 

 

Interfaces in Java


1. Introduction of Interface

·         An interface in Java is like a blueprint of a class.

·         It contains abstract methods (methods without body) and constants.

·         Interfaces help achieve 100% abstraction (before Java 8) and multiple inheritance.

·         A class that implements an interface must provide implementations for all its methods.

·         Introduced mainly to overcome single inheritance limitation in Java.


2. Declaration of Interface

·         Declared using the interface keyword.

·         Methods are public and abstract by default.

·         Variables are always public static final.

Syntax

interface InterfaceName {
    // constant
    int VALUE = 100;   // public static final by default
 
    // abstract method
    void abstractMethod();
 
    // default method (Java 8 onwards)
    default void defaultMethod() {
        System.out.println("This is a default method");
    }
 
    // static method (Java 8 onwards)
    static void staticMethod() {
        System.out.println("This is a static method");
    }
}

3. Implementation of Interface

·         A class uses the implements keyword to use an interface.

·         The class must implement all abstract methods of the interface.

·         If not, the class must be declared abstract.

Example

// Declaration of Interface
interface Animal {
    void sound();   // abstract method
    void eat();     // abstract method
}
 
// Implementation of Interface
class Dog implements Animal 
{
    @Override
    public void sound() 
    {     System.out.println("Dog barks");    }
 
    @Override
    public void eat() 
    {     System.out.println("Dog eat biscuits");   }
}
 
// Main Class
public class Main 
{
    public static void main(String[] args) 
    {
        Animal a = new Dog();  // reference of interface
        a.sound();  // Dog barks
        a.eat();    // Dog eats meat
    }
}
 
 
In Java we can achieve multiple inheritance with the concept of Interfaces

 

interface add1

{

    void add(int a,int b);

}

 

interface sub1

{

    void sub(int a,int b);

}

 

class cal implements add1,sub1

{

    public void add(int a, int b)

    {

        System.out.println("Addition is : "+(a+b));

    }

    public void sub(int a,int b)

    {

        System.out.println("Subtraction is : "+(a-b));

    }

   

}

 

 

public class Interface2

{

    public static void main(String[] args)

    {

        cal c = new cal();

        c.add(20, 30);

        c.sub(50, 10);

    }

 

}

 

 

 

  

 

 

 

Nested Interfaces

 

In Java, an interface can be declared inside another class or interface.
It is used to group logically related functionality or to hide implementation details.

 

Types of Nested Interfaces

1.      Interface inside a Class

·         Declared as a member of a class.

·         It can be public, private, or protected.

·         If it is private, it can only be accessed within the outer class.

2.      Interface inside another Interface

·         Always public and static by default.

·         Can be accessed using OuterInterface.InnerInterface.


1️ Interface Inside a Class

Example

class Outer {
    // Nested Interface
    interface Message {
        void showMessage();
    }
}
 
// Class implementing the nested interface
class Inner implements Outer.Message {
    public void showMessage() {
        System.out.println("Hello from Nested Interface inside a Class!");
    }
}
 
public class Main {
    public static void main(String[] args) {
        Outer.Message obj = new Inner();  // Access using Outer.InterfaceName
        obj.showMessage();
    }
}

Output

Hello from Nested Interface inside a Class!

2️ Interface Inside Another Interface

Example

interface Parent {
    void display();
 
    // Nested Interface
    interface Child {
        void show();
    }
}
 
// Implementing nested interface
class Demo implements Parent.Child {
    public void show() {
        System.out.println("Nested Interface inside another Interface!");
    }
}
 
public class Main2 {
    public static void main(String[] args) {
        Parent.Child obj = new Demo();  // Access using Parent.Child
        obj.show();
    }
}

Output

Nested Interface inside another Interface!

 

 

 

Inheritance of Interfaces in Java

Just like classes can extend other classes, interfaces can also extend other interfaces.

Note: We can’t inherit more than one class but we can inherit more than one interface.

·         An interface can extend multiple interfaces (supports multiple inheritance).

·         A class that implements the child interface must provide implementations for all abstract methods of both parent and child interfaces.


Syntax

interface hello2

{

   

}

 

interface hello3 extends hello1, hello2

{

   

}

 

class temp implements hello3

{

   

}

 

 

 

Key Points

1.      Single Inheritance of Interface

o    One interface extends another interface.

2.  interface A {
3.      void display();
4.  }
5.  interface B extends A {
6.      void show();
7.  }

8.      Multiple Inheritance of Interface

o    One interface can extend multiple interfaces.

9.  interface C extends A, B {
10.    void print();
11.}

12.  Difference from Class Inheritance

o    Classes → can extend only one class (single inheritance).

o    Interfaces → can extend multiple interfaces (multiple inheritance supported).

 

 

What is a Default Method?

·         A default method is a method inside an interface that has a method body.

·         Declared using the keyword default.

·         Allows you to add new functionality to an interface without forcing existing classes to implement it.

 

Syntax

interface InterfaceName {

    default void methodName() {

        // method body

    }

}

 

Example

interface Vehicle {

    void start(); // abstract method

 

    // default method

    default void stop() {

        System.out.println("Vehicle stopped (Default Method).");

    }

}

 

class Car implements Vehicle {

    public void start() {

        System.out.println("Car started.");

    }

 

    // Overriding default method (optional)

    @Override

    public void stop() {

        System.out.println("Car stopped safely (Overridden).");

    }

}

 

public class Main {

    public static void main(String[] args) {

        Vehicle myCar = new Car();

        myCar.start(); // abstract method

        myCar.stop();  // default method (overridden version will run)

    }

}

 

Output

Car started.

Car stopped safely (Overridden).

 

 

Key Features of Default Methods

1.      Declared using the default keyword inside an interface.

2.      Provide method body inside the interface.

3.      Optional to override in implementing classes.

4.      Used to add new methods to interfaces without breaking existing implementations.

5.      Can be called using:

o    Object reference of implementing class.

o    Interface reference.

 

 

 

 

 

 

Key Points

1.      Declared using the interface keyword.

2.  interface Animal { }

3.      Methods:

o    By default, methods are public and abstract (till Java 7).

o    From Java 8, interfaces can also have:

§  default methods (with body).

§  static methods.

o    From Java 9, interfaces can have:

§  private methods (to be used inside the interface).

4.      Variables:

o    Always public static final (constants).

o    Must be initialized at declaration.

5.      Implementation:

o    A class implements an interface using the implements keyword.

o    A class must implement all abstract methods of the interface, or else declare itself abstract.

6.      Inheritance:

o    One interface can extend multiple interfaces.

o    A class can implement multiple interfaces (this is how Java achieves multiple inheritance).

 

 

 

Static Methods in Interfaces (Java 8)

Java 8 introduced static methods inside interfaces to allow utility or helper methods to be defined directly within the interface itself.

Before Java 8, interfaces could only contain:

·         public abstract methods

·         public static final constants

Static methods expanded the capability of interfaces by allowing method definitions with a body.


🔑

Key Points

1.      Declared using the static keyword inside the interface.

2.      Must have a method body (unlike abstract methods).

3.      Can be called only using the interface name.

o    Not inherited by implementing classes.

o    Not overridden by implementing classes.

4.      Used for utility functions related to the interface.


Syntax

interface InterfaceName {
    static void staticMethodName() {
        // method body
    }
}

Example Program

interface Vehicle {

    void start(); // abstract method

 

    // static method

    static void service() {

        System.out.println("Vehicle servicing (Static Method).");

    }

}

 

 

 

// Class implementing the interface

class Car implements Vehicle {

    public void start() {

        System.out.println("Car started.");

    }

}

 

public class Main {

    public static void main(String[] args) {

        Vehicle myCar = new Car();

        myCar.start();       // Call abstract method implementation

 

        // Static method is called using interface name

        Vehicle.service();   // Correct

        // myCar.service();  // Error: Cannot call static method with object reference

    }

}



Program :



interface Bank

{

void loan();

void withdraw();

void deposit();

}

interface Temp

{

}

interface BankDetails extends Bank, Temp

{

void account();

void minbalance();

}


abstract class Test11 implements Bank

{

public void loan()

{

System.out.println("Loan");

}

public void withdraw()

{

System.out.println("Withdraw");

}

}


abstract class Test22 extends Test11

{

public void deposit()

{

System.out.println("Deposit");

}

public void minbalance()

{

System.out.println("minbalance");

}

}


class Demo11 extends Test22

{

public void account()

{

System.out.println("acc details");

}

}



public class Interface3 extends Object

{

public static void main(String[] args)

{

new Demo11().account();

}


}



Difference Between Array and Vector in Java

Feature

Array

Vector

Nature

Fixed-size elements of the same data type.

Dynamic-size collection that can grow or shrink, implements the List interface.

Size Modification

Cannot be resized once initialized.

Can grow or shrink dynamically as needed.

Performance

Generally faster as it is a simple data structure

Slower than arrays due to dynamic array and synchronized methods.

Synchronization

Not synchronized.

Synchronized. All methods are synchronized, making it thread-safe

Data Type

Can hold primitives or objects.

Can only hold objects.

Iteration

Can use a simple for-loop or for-each loop.

Can use Iterator, ListIterator, Enumeration, for-loop, or for-each loop.

Utilities

Does not have built-in methods for manipulation

Provides methods for manipulation (e.g., add, remove, clear).

 

 

No comments:

Post a Comment

Unit 3 - CSE B

  Java Inheritance   ( ‘ IS-A ’ relationship)   It is a mechanism in which one object acquires all the properties and behaviors of a par...