java代码在子类中是如何工作的?
package practice;
class person{
private String firstname;
private String lastname;
public person(String firstname,String lastname){
set_first(firstname);
set_last(lastname);
}
public String get_first() {
return firstname;
}
public void set_first(String firstname) {
this.firstname=firstname;
}
public void set_last(String lastname) {
this.lastname=lastname;
}
public String get_last() {
return lastname;
}
}
class employee extends person {
private int empid;
public employee(String firstname, String lastname, int empid) {
super(firstname,lastname);
set_empid(empid);
}
public void set_empid(int empid) {
this.empid=empid;
}
public int get_empid() {
return empid;
}
}
class testing_super_keyword {
public static void main(String args[]) {
employee emp=new employee("Paul","Anderson",1234);
System.out.println(emp.get_first()+" "+emp.get_last());
System.out.println(emp.get_empid());
}
}
这里有两个类,person超类和employee子类。所以我只想知道这段代码不应该作为firstname工作,而lastname变量在超类中是私有的?但是子类employee是如何继承和使用这些成员的呢
我认为超类的私有变量不能被继承,所以为什么它在这里工作得很好呢
我完全糊涂了,请帮忙
# 1 楼答案
虽然父类的私有变量不是由子类(即employee)继承的,但是有一些公共函数称为
getter
和setter
,允许从其子类访问类的私有成员您可以看到,当您想从父对象访问firstname时,您将从employee对象调用
get_first()
来获取firstname。如果你想设置名字,你可以调用set_first("name")
来设置名字。希望能有所帮助# 2 楼答案
是的,你完全正确,他们不会继承。但是在您的代码中,您没有直接访问这些字段,对吗
在这里,您将参数(从主方法)传递到
employee
构造函数,参数的名称类似于person
中的字段,但它们不同。您可以像这样更改参数名称,它仍然可以正常工作这里参数值被带入
super
类构造函数中,初始化其私有字段,然后初始化employee
的empid
在这里,您也不是直接访问
private
字段,而是调用公共方法,这些方法将继承到employee
并可在其引用中调用将类的成员保持为私有,将其行为(方法)保持为公共是
encapsulation
的一部分,这样您就不能直接访问它,而是可以使用公共方法设置和获取它的值PS:如果IDE提供了选项,请尝试使用IDE生成getter和setter,并尝试遵循类和方法的命名约定
# 3 楼答案
让我们在此处查看如何初始化firstname和lastname:
super(firstname,lastname)
,firstname和lastname传递给要处理的父级(即人员)李>set_first(firstname)
和set_last(lastname)
,参数firstname和lastname将在父类本身中使用从子构造函数(即Employee)传递的值进行设置如果要直接在Employee类中将私有变量初始化为: