1
Answer

write program and explain inheritance inn J#

write program and explain inheritance inn J#

Answers (1)
0
Shivam Payasi

Shivam Payasi

10 21.1k 27.4k 1y

Sure, here's an example of a program that demonstrates inheritance in J#:

import system.*;

// Base class
class Animal {
    protected String species;

    public Animal(String species) {
        this.species = species;
    }

    public void eat() {
        Console.WriteLine("The " + species + " is eating.");
    }

    public void sleep() {
        Console.WriteLine("The " + species + " is sleeping.");
    }
}

// Derived class
class Dog extends Animal {
    public Dog() {
        super("Dog");
    }

    public void bark() {
        Console.WriteLine("The dog is barking.");
    }
}

// Main class
class Program {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat(); // Inherited from Animal class
        dog.sleep(); // Inherited from Animal class
        dog.bark(); // Defined in Dog class
    }
}

Explanation:

In this program, we have a base class called `Animal` that has two methods, `eat()` and `sleep()`, and a protected variable `species`. The `Animal` class serves as the parent class.

We also have a derived class called `Dog` that extends the `Animal` class. The `Dog` class inherits the methods and variables from the `Animal` class and adds a new method called `bark()`. The `Dog` class serves as the child class.

In the `main()` method of the `Program` class, we create an instance of the `Dog` class called `dog`. We can then call the inherited methods `eat()` and `sleep()` from the `Animal` class using the `dog` object. Finally, we call the `bark()` method defined in the `Dog` class.

This demonstrates the concept of inheritance in J#. The child class (`Dog`) inherits the properties and behaviors of the parent class (`Animal`) and can also add its own unique properties and behaviors.

Next Recommended Forum