how to create a derived class in Java

how to create a derived class in Java

To create a derived class in Java, you can use inheritance.

In Java, a class can inherit the properties and methods of another class by extending it. The class that is being inherited is called the base class or superclass, and the class that is inheriting is called the derived class or subclass.

Here is an example of how you can create a derived class in Java:

refer to:‮ual‬tturi.com
// Base class
class Animal {
  int age;
  String name;

  public Animal(int age, String name) {
    this.age = age;
    this.name = name;
  }

  public void eat() {
    System.out.println("Animal is eating.");
  }

  public void sleep() {
    System.out.println("Animal is sleeping.");
  }
}

// Derived class
class Dog extends Animal {
  String breed;

  public Dog(int age, String name, String breed) {
    super(age, name);
    this.breed = breed;
  }

  public void bark() {
    System.out.println("Dog is barking.");
  }
}

This code defines a base class called Animal that has two instance variables, age and name, and two methods, eat and sleep. It also defines a derived class called Dog that extends the Animal class and adds a new instance variable called breed and a new method called bark.

The Dog class has a constructor that calls the constructor of the base class using the super keyword and passes the values of the age and name parameters to it. It also initializes the breed instance variable with the value of the breed parameter.

The Dog class has access to all the public and protected members of the base class, and can override them if necessary. It can also define new methods and variables that are specific to the derived class.

You can create an object of the derived class using the new operator and the constructor of the class.

Here is an example of how you can create an object of the Dog class and call its methods:

Dog dog = new Dog(3, "Buddy", "Labrador");
dog.eat();  // Output: "Animal is eating."
dog.sleep();  // Output: "Animal is sleeping."
dog.bark();  // Output: "Dog is barking."

This code creates a new Dog object called dog and calls its eat, sleep, and bark methods.

Created Time:2017-11-01 12:05:16  Author:lautturi