+ 4
Inheritance
Could you explain inheritance to me , please With a simple example?!
10 Answers
+ 11
That's a part of OOP.
Imagine you have an ANIMAL. How many animals do you know? Many! Now your animal has an attribute: 'type' which can take the values bird, fish and so on. It propably has an amount l of legs and it can make a sound.
You get yourself a pet now: A Dog. A dog is an animal, so everything that's true for an animal is also true for a dog. So dog inherits from animal and can now use all of it's properties. It has 4 legs, can make the sound "Woof" and so on.
Here it is in Java:
public class Animal {
int legs;
String type;
....
public void makeSound() {
System.out.println ("Grr");
}
}
public class Dog extends Animal {
int legs = 4;
...
@Override
public void makeSound() {
System.out.println("Woof");
}
}
Now there are different races... Different size, patterns in fur and so on. So a GoldenRetriever maybe inharits from Dog!
I know this is not the best example...
But you can literally go around at home and look for things that are extensions of other things. A few examples:
Apple->Fruit
Boot, FlipFlop -> Shoe
Windows, Linux -> Operating System
iPhone, Samsung phones -> mobile
...
Did that help?
+ 5
if you have a class with properties and methods, and you want make another class with same functions but want to add more to it, you inherit the interface of the first class
+ 2
D B
Thanks so much
Very useful
+ 1
Thanks a lot
+ 1
Thanks for that
+ 1
You're welcome!
0
D B
Thanks so much
Very useful