Mark As Completed Discussion

Inheritance

In object-oriented programming, inheritance is a mechanism that allows a class to inherit the properties and methods of another class. The class that inherits from another class is called the subclass, and the class that is inherited from is called the superclass.

In Java, inheritance is achieved using the extends keyword. The subclass can access all the non-private members (fields and methods) of the superclass. This allows for code reuse and promotes the concept of code organization and hierarchy.

Here's an example that demonstrates inheritance in Java:

TEXT/X-JAVA
1// Parent class
2public class Animal {
3
4    protected String name;
5    protected int age;
6
7    public Animal(String name, int age) {
8        this.name = name;
9        this.age = age;
10    }
11
12    public void eat() {
13        System.out.println(name + " is eating");
14    }
15
16    public void sleep() {
17        System.out.println(name + " is sleeping");
18    }
19}
20
21// Child class
22public class Dog extends Animal {
23
24    private String breed;
25
26    public Dog(String name, int age, String breed) {
27        super(name, age);
28        this.breed = breed;
29    }
30
31    public void bark() {
32        System.out.println(name + " is barking");
33    }
34}
35
36public class Main {
37    public static void main(String[] args) {
38        Dog dog = new Dog("Max", 2, "Labrador");
39        dog.eat();
40        dog.sleep();
41        dog.bark();
42    }
43}

In this example, we have a parent class Animal that has a constructor and two methods: eat() and sleep(). The child class Dog extends the Animal class using the extends keyword. The Dog class has its own constructor and method bark(). In the Main class, we create an instance of the Dog class and demonstrate how inheritance allows us to access the methods from both the parent and child class.

By using inheritance, we can create a hierarchy of classes, with each class inheriting properties and behaviors from its parent class. This helps to organize and structure code in a logical and reusable manner.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment