OOPS – Inheritance

Inheritance is used for code-reusability. Inheritance is a mechanism wherein a new class is derived from an existing class. In Java, classes may inherit or acquire the properties and methods of other classes. A class derived from another class is called a subclass, whereas the class from which a subclass is derived is called a superclass.

1. Dog Class

Java

1

2

3

4

5

6

packageoops;

publicclassDogextendsAnimal{

}

2. Fish Class

Java

1

2

3

4

5

6

packageoops;

publicclassFishextendsAnimal{

}

3. Animal Class

Java

1

2

3

4

5

6

7

8

9

10

11

packageoops;

publicclassAnimal{

inti=10;

publicvoidspeak()

{

System.out.println("I can speak well");

}

}

4. Runner Class

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

packageoops;

publicclassRunner{

publicstaticvoidmain(String[]args){

Dog dog=newDog();

Fish fish=newFish();

dog.speak();

fish.speak();

System.out.println(dog.i);

System.out.println(fish.i);

}

}

Please share your feedback and share the post. Contact us at online.nimit@gmail.com