Inheritance allows a class to acquire properties and methods from another class.
class Animal {
void sound() { System.out.println("Sound"); }
}
class Dog extends Animal {
void bark() { System.out.println("Bark"); }
}
Feature | Abstract Class | Interface |
---|---|---|
Inheritance | Single inheritance | Multiple inheritance |
Methods | Can have implemented and abstract methods | Default methods (since Java 8) |
Fields | Can have variables | Only constants |
Constructors | Allowed | Not allowed |
Constructors are special methods used to initialize objects.
class MyClass {
MyClass() {
System.out.println("Constructor");
}
}