java Inheritance, Composition, Sealed classes



Inheritance allows a class to acquire the properties and behaviours of another class, promotes reusability. 
// Superclass
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}

// Subclass
class Dog extends Animal {
void wagTail() {
System.out.println("Dog wags tail");
}
}

Interfaces

Unlike classes, a class can implement multiple interfaces, helping to avoid the diamond problem present in some other languages.
// Implementing multiple interfaces
class Duck implements Flyable, Swimmable {
public void fly() {
System.out.println("Duck flies");
}

public void swim() {
System.out.println("Duck swims");
}
}

Class Visibility and Its Impact

ModifierCan be inherited fromAccessible in other packages?
public✅ Yes✅ Yes
protected✅ Yes (subclass only)✅ Yes (if subclass)
default (no modifier)✅ Yes (same package only)❌ No
private❌ No❌ No

Method Overriding:
  • The method must have the same name, return type, and parameters.

  • The method being overridden cannot be private, static, or final.

  • The overriding method cannot reduce visibility.

class Animal {
void makeSound() {
System.out.println("Animal makes sound");
}
}

class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meows");
}
}
public void main(String[] args) {
Animal myPet = new Cat();
myPet.makeSound(); // Cat meows
}
The final Keyword

The final keyword puts restrictions on inheritance and method overriding:
Use Case                      Effect
final class                   🛑 Can't be subclassed
final method                  🚫 Can't be overridden
final variable               📌 Becomes constant—value can't change after assign

Composition
Instead of inheriting behaviours from a parent class, composition means building complex types by combining objects of other classes. Composition promotes code reuse and flexibility, often favoured over inheritance in many design patterns.

Sealed classes
It allows us to explicitly define which classes or interfaces are allowed to extend or implement a sealed type.
public sealed class Shape permits Circle, Square, Triangle {
// Common methods or fields for all shapes
public abstract double calculateArea();
}
Any class or interface permitted to extend/implement (Circle, Square, Triangle here) a sealed type must explicitly define its role in the hierarchy using one of three modifiers:
1. final: The subclass cannot be extended further.
public final class Circle extends Shape { ... }
2. sealed: The subclass itself is also sealed, meaning it can only be extended by its own permitted subclasses.
public sealed class Rectangle extends Shape permits FilledRectangle { ... }
3. non-sealed: The subclass opens up the hierarchy again, allowing any other class to extend it without restriction.
public non-sealed class Square extends Shape { ... }
Sealed in Switch expression:
public static String getShapeInfo(Shape shape) {
return switch (shape) {
case Circle c -> "This is a Circle with radius: " + c.getRadius();
case Square s -> "This is a Square with side: " + s.getSide();
case Rectangle r -> "This is a Rectangle with length " + r.getLength() + " and width " + r.getWidth();
// No default case needed! The compiler knows all cases are covered.
};
}

Questions:
  1. Can a class in Java extend multiple classes? Yes
  2. What is the purpose of the 'super' keyword in Java?  The super keyword is used to call a method or constructor from the superclass. For example, super.methodName() calls a method from the parent class.
  3. Is it true: Method overriding requires the method to have the same name, return type, and parameters as the method in the superclass. It cannot be private or static. ? Yes
  4. What happens if a method is declared as final in a superclass?  final method cannot be overridden in a subclass. This ensures that the method's implementation remains unchanged.
  5. What is the default visibility of a class in Java? The default visibility of a class in Java is package-private, meaning it is accessible only within the same package.
  6. Can a class implement multiple interfaces in Java? Yes, a class can implement multiple interfaces in Java. This allows for multiple inheritance of behaviour.
  7. What is the difference between abstract classes and interfaces in Java? Abstract classes can have implemented methods, while interfaces (prior to Java 8) could only have abstract methods. From Java 8 onwards, interfaces can also have default and static methods.
Programs:
Animal Hierarchy Create a class Animal with methods like eat() and sleep(). Then, create subclasses like Dog, Cat, and Bird that inherit from Animal and override the eat() method to provide specific behaviour for each animal.

Bank Account System Create a base class BankAccount with attributes like accountNumber and balance. Create subclasses like SavingsAccount and CurrentAccount that add specific behaviours, such as calculateInterest() for SavingsAccount.

Employee Management System Create a base class Employee with attributes like name and salary. Create subclasses like Manager and Developer that add specific attributes (e.g., teamSize for Manager) and methods (e.g., writeCode() for Developer).

Final Keyword Usage Create a class MathConstants with a final method getPiValue(). Try to override this method in a subclass and observe the compilation error.

Library System using composition : Simple system to manage a library's books, authors, and publishing details. Use composition to embed Author and Publisher objects inside the Book class. Demonstrate how each book has its own associated author and publisher:

Followings are the class details:
1. Author
Fields: name, email, birthYear
Method: getAuthorDetails()

2. Publisher
Fields: name, location, contactNumber
Method: getPublisherDetails()

3. Book
Fields: title, genre, isbn
Composition:
Contains an Author object
Contains a Publisher object
Methods:
getBookDetails() – returns details including author and publisher info.