Inheritance is a key concept in object-oriented programming that allows one class to inherit the properties and behaviors of another class.
Here’s how it works: say we have a class called “Animal” that has certain characteristics, like the ability to move and make noise. We can then create a new class called “Dog” that inherits from the Animal class, meaning it will have all of the characteristics of an Animal, plus any additional characteristics that are unique to a Dog. This allows us to reuse code and avoid having to write the same characteristics for every individual animal class.
In Java, we use the “extends” keyword to indicate that a class is inheriting from another class. For example:
public class Dog extends Animal {
// additional characteristics and behaviors unique to a Dog go here
}
We can also use the “super” keyword to access the characteristics and behaviors of the parent class within the child class. This is useful if we want to override a behavior that is inherited from the parent class.
Inheritance is just one of the many tools that Java provides for object-oriented programming, and it can be a powerful way to organize and reuse code in your projects.
You could implement an Animal
class in Java:
public class Animal {
private String name;
private int age;
private String species;
public Animal(String name, int age, String species) {
this.name = name;
this.age = age;
this.species = species;
}
public void makeNoise() {
System.out.println("Some generic noise");
}
public void move() {
System.out.println("The animal is moving");
}
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;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
}
This Animal
class has three instance variables: name
, age
, and species
. It also has a constructor that allows you to create an Animal
object with a specific name, age, and species. It has three methods: makeNoise
, move
, and getters
/setters
for each instance variable.