Java-继承-访问继承的变量和方法

时间:2020-02-23 14:36:38  来源:igfitidea点击:

在本教程中,我们将学习如何在Java编程语言中使用继承的变量和方法。

在上一个教程Java-继承中,我们了解了继承。

因此,我们讨论了父类" Person"和子类" Employee"。
现在让我们增强该示例,并向父类添加一些方法并在子类中使用它。

在以下示例中,我们将方法添加到父类" Person"中,该方法将由子类" Employee"继承。

//the parent class
class Person {
  //general member variables
  String firstname;
  String lastname;

  //general methods
  public void setFirstName(String firstname) {
    this.firstname = firstname;
  }

  public void setLastName(String lastname) {
    this.lastname = lastname;
  }
}

//the child class inheriting the parent class
class Employee extends Person {
  //specific member variables
  String employeeid;
  int payscale;
  String joiningDate;

  //constructor
  Employee(String firstname, String lastname, String employeeid, int payscale, String joiningDate) {
    
    //set the firstname and lastname using the
    //setFirstName() and setLastName() methods
    //of the parent class Person
    //that is inherited by this child class Employee
    this.setFirstName(firstname);
    this.setLastName(lastname);

    //now set the member variables of this class
    this.employeeid = employeeid;
    this.payscale = payscale;
    this.joiningDate = joiningDate;
  }

  //show employee details
  public void showDetail() {
    System.out.println("Employee details:");
    System.out.println("EmployeeID: " + this.employeeid);
    System.out.println("First name: " + this.firstname);
    System.out.println("Last name: " + this.lastname);
    System.out.println("Pay scale: " + this.payscale);
    System.out.println("Joining Date: " + this.joiningDate);
  }
}

//the main class
public class Example {
  
  //the main method
  public static void main(String[] args) {

    //employee data
    String firstname = "";
    String lastname = "";
    String employeeid = "E01";
    int payscale = 3;
    String joiningDate = "2010-01-01";

    //creating an object of the Employee class
    Employee empObj = new Employee(firstname, lastname, employeeid, payscale, joiningDate);

    //show detail
    empObj.showDetail();

  }
}
$javac Example.java 
$java Example
Employee details:
EmployeeID: E01
First name: 
Last name: 
Pay scale: 3
Joining Date: 2010-01-01

因此,当" Employee"类继承" Person"类时,它将转换为以下内容。

class Employee {
  //inherited variables from parent class
  String firstname;
  String lastname;

  //inherited methods from parent class
  public void setFirstName(String firstname) {
    this.firstname = firstname;
  }

  public void setLastName(String lastname) {
    this.lastname = lastname;
  }

  //variables of the Employee class
  String employeeid;
  int payscale;
  String joiningDate;

  //constructor
  Employee(params_list) {
    //some code...
  }

  //method of the Employee class
  public void showDetail() {
    //some code...
  }
}