Inheritance in java

 Inheritance in java


Inheritance is a mechanism in Java that allows a class to inherit properties and behavior from another class. Here is an example of a class that inherits from the Person class:



public class Student extends Person {

  private String major;


  public Student(String name, int age, String major) {

    super(name, age);

    this.major = major;

  }


  public String getMajor() {

    return this.major;

  }


  public void setMajor(String major) {

    this.major = major;

  }

}

In this example, we define a class called Student that extends the Person class. The Student class has an additional instance variable (major) and two methods (getMajor and setMajor). The super keyword is used to call the constructor of the Person class and initialize the name and age instance variables.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...