+ 3
What is inheritance ???
2 Answers
+ 1
Inheritance refers to the "handing down" of traits possessed by a parent element. If you code a function within a function, that "child" function will "Inherit" some of the traits that the "Parent" function has set for it. (Unless explicitly told not to) Hope this helps!
+ 1
Inheritance allows you to easily share code between multiple classes. This includes methods and fields.
For example, let's say that you are making a game, which will need some animals. You can create an animal superclass:
public class Animal {
// traits that all animals (of any type) must have:
private int health = 100;
// behavior (methods) that all animals (of any type) must have:
public int getHealth() {
return health;
}
public void damge(int damage) {
health -= damage; // subtract 'damage' from this animals health
}
}
So now, whenever we want to make a new type of animal, we extend the animal class:
public class Dog extends Animal {
// traits that all dogs must have
private DogBreed breed = //...
// behavior that all dogs must have:
public void bark() {
System.out.println("Bark!");
}
}
Now, if you create a new Dog object:
Dog dog = new Dog();
You can call the dog's method (of course):
dog.bark();
But you can also use the Dog object to call a method defined in the Animal class:
dog.damage(1); // we don't have to re-redefine this in the dog class, because the Animal class (Dog's superclass) already defines this method.
It is also possible to override a method (so if we wanted to make dogs invincible - which, of course, we do!). This can be done by copying the superclass's method header (which is the stuff at the top, such as the return type, method name, parameters, etc):
@Override // optional line, indicates that this method overrides a superclass method
public void damage(int damage) {
// do nothing - we don't want this dog to take damage!
}
Inheritance is very powerful, and definitely a topic worth looking into.