Inheritance is one of the fundamental principles of object-oriented programming. Inheritance allows a class (subclass) to inherit characteristics and behaviors from another class (superclass). Here are some ways Java supports inheritance:
Keyword "extends"
The "extends" keyword is used to establish an inheritance relationship between two classes. The subclass extends the superclass, thus acquiring the attributes and methods of the superclass.
public class Animal {
// superclass attributes and methods
}
public class Dog extends Animal {
// subclass-specific attributes and methods
}
// superclass attributes and methods
}
public class Dog extends Animal {
// subclass-specific attributes and methods
}
Attributes and Methods Inheritance
The subclass inherits attributes and methods from the superclass, allowing code reuse.Dog myDog = new Dog();
myDog.setName("Rex"); // Animal superclass method
myDog.bark(); // Dog subclass specific method
myDog.setName("Rex"); // Animal superclass method
myDog.bark(); // Dog subclass specific method
Method "super"
The "super" keyword is used to call superclass methods or access attributes from the subclass.public class Dog extends Animal {
public void bark() {
super.makeSound(); // calls method makeSound() of superclass Animal
System.out.println("Dog Barking");
}
}
public void bark() {
super.makeSound(); // calls method makeSound() of superclass Animal
System.out.println("Dog Barking");
}
}
Override
The subclass can provide a specific implementation for a method that is already defined in the superclass. This is known as method overriding.
@Override
public void makeSound() {
System.out.println("Dog Barking");
}
Polymorphism
Polymorphism is supported in Java, allowing references from a superclass to be used to manipulate objects from subclasses.
Animal myAnimal = new Dog(); // polymorphism
myAnimal.makeSound(); // invoke the specific Dog subclass method
Constructors in the Inheritance Hierarchy
Constructors in the inheritance hierarchy are called in the correct order, ensuring that necessary initializations are made to all classes.
public class Animal {
public Animal() {
System.out.println("Animal superclass constructor");
}
}
public class Dog extends Animal {
public Dog() {
super(); // call the Animal superclass constructor
System.out.println("Dog subclass constructor");
}
}
These are some main aspects through which Java supports inheritance. It is a powerful tool for creating class hierarchies, promoting code reuse, flexibility and extensibility in object-oriented software development.
Nenhum comentário:
Postar um comentário