Junior — Middle
What is meant by inheritance of properties and characteristics in object-oriented programming?
sobes.tech AI
Answer from AI
In object-oriented programming, inheritance is a mechanism that allows one class (the subclass) to automatically acquire the properties and methods of another class (the superclass). This enables code reuse and the creation of class hierarchies, where more specialized classes extend or refine the behavior of basic classes.
For example, if there is a class Animal with common properties (such as name, age) and methods (move(), makeSound()), then a class Dog can inherit these properties and methods, adding its own unique ones, such as bark().
In Java, inheritance is implemented using the extends keyword:
class Animal {
String name;
void move() {
System.out.println("Animal moves");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
Thus, Dog inherits the name field and the move() method from Animal.