Dezign Patterns
Inheritance
📦 Definition: One class (child/subclass) inherits the properties and behavior of another (parent/superclass).🎯 Intent : Code reuse and logical hierarchy.
class Vehicle {
void startEngine() {
System.out.println("Engine started.");
}
}
class Car extends Vehicle {
void playMusic() {
System.out.println("Playing music.");
}
}
interface A {
default void hello() {
System.out.println("Hello from A");
}
}
interface B {
default void hello() {
System.out.println("Hello from B");
}
}
class MyClass implements A, B {
// Must override hello() to resolve ambiguity
public void hello() {
A.super.hello(); // Or B.super.hello();
}
}
Feature | Java 7 | Java 8 |
Multiple class inheritance | ❌ | ❌ |
Multiple interface inheritance | ✅ | ✅ |
Multiple inheritance of behavior | ❌ | ✅ (now with default methods!) |
Multiple inheritance of state | ❌ | ❌ |
Though they say the java supports multiple inheritance , but it doesn't support "Multiple inheritance of state"
class A {
String test;
public void display() {
System.out.println(test);
}
}
class B {
String test;
public void display() {
System.out.println(test);
}
}
// class can't extent multiple classes -- compile time error
class C extends A , B {
@Override
public void display() {
System.out.println(super.test);
}
}