FAQ Part 4: Object-Oriented Programming in Java

What is inheritance?

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"); }
}

What is the difference between an abstract class and an interface?

FeatureAbstract ClassInterface
InheritanceSingle inheritanceMultiple inheritance
MethodsCan have implemented and abstract methodsDefault methods (since Java 8)
FieldsCan have variablesOnly constants
ConstructorsAllowedNot allowed

What are constructors?

Constructors are special methods used to initialize objects.

class MyClass {
  MyClass() {
    System.out.println("Constructor");
  }
}