In Java, inheritance is a mechanism that allows a class to inherit properties and behaviors from another class. Setters and getters are methods that are commonly used to set and get the values of object properties.
Here is an example of inheritance and setters and getters in Java:
class Animal { // Properties private String name; private int age; // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } class Dog extends Animal { // Properties and methods of the Dog class } public class InheritanceExample { public static void main(String[] args) { Dog dog = new Dog(); // Set the dog's name and age using the setters dog.setName("Fido"); dog.setAge(5); // Get the dog's name and age using the getters String name = dog.getName(); int age = dog.getAge(); System.out.println("Dog's name: " + name); System.out.println("Dog's age: " + age); } }
In this example, the Dog
class is a subclass of the Animal
class and inherits the name
and age
properties and the corresponding setters and getters. The InheritanceExample
class creates a Dog
object and sets its name and age using the setters, and then gets the name and age using the getters.
Output:
Dog's name: Fido Dog's age: 5
Inheritance allows you to reuse code and avoid duplication, and setters and getters are a convenient way to set and get the values of object properties. Together, inheritance and setters and getters can make it easier to manage and manipulate object data in your Java programs.