gpt4 book ai didi

java - 如何限制子类访问父类(super class)方法?

转载 作者:行者123 更新时间:2023-12-01 12:45:22 25 4
gpt4 key购买 nike

例如:

我有课

package test.inheritance.checkMultiple;

public class Company {



protected void run (){
System.out.println("Time to Run");
}

}

public class Department extends Company {



public void testDepartment()
{
Department d =new Department();
d.run();
}

}


public class Employee extends Department{


public void checkValidEmployee(){
Employee e =new Employee();
e.run();
e.testDepartment();

}

public static void main (String[] artgs)
{
Employee e =new Employee();
e.checkValidEmployee();
System.out.println("Valid Emplyee");
}

}

1) 我不希望员工类有权访问 run 方法。为此我该怎么办?

2)如果我想给员工类访问run方法,但不给部门类,我该怎么办?

最佳答案

你不应该这样做,因为每个子类都必须是它所属子类的有效类 - 请参阅 Liskovs substitution principle .

因此,按照 @Michael Laffargue 的建议,使用组合而不是继承

我不知道你到底想要实现什么,但它应该看起来更像下面这样,其中 Company 是 Department 的成员变量,而 Department 又是 Employee 的成员变量。

import java.util.Arrays;
import java.util.List;

public class Company
{
private final String name;

public Company(String name)
{
this.name = name;
}

public String getName()
{
return this.name;
}

public void run()
{
System.out.println("Time to Run");
}
}

public class Department
{
private static final List<String> VALID_DEPARTMENTS = Arrays.asList("IT");
private final String name;
private final Company company;

public Department(String name, Company company)
{
this.name = name;
this.company = company;
}

public String getName()
{
return this.name;
}

public Company getCompany()
{
return this.company;
}

public void checkValid()
{
if (!VALID_DEPARTMENTS.contains(this.name))
throw new AssertionError();
}

}

public class Employee
{
private final Department department;
private final String name;

public Employee(String name, Department department)
{
this.department = department;
this.name = name;
}

public void checkValid()
{
this.department.getCompany().run();
this.department.checkValid();
}

public Department getDepartment()
{
return this.department;
}

public String getName()
{
return this.name;
}
}

public class Main
{
public static void main(String[] artgs)
{
final Company company = new Company("Company");
final Department department = new Department("IT", company);
Employee e = new Employee("Peter", department);
e.checkValid();
System.out.println("Valid Emplyee");
}
}

关于java - 如何限制子类访问父类(super class)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24754712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com