gpt4 book ai didi

java - 私有(private)成员的继承

转载 作者:行者123 更新时间:2023-12-02 06:13:04 25 4
gpt4 key购买 nike

    class Quadrilateral
{
private Point TL;
private Point TR;
private Point BR;
private Point BL;
public Quadrilateral(Point p1, Point p2, Point p3, Point p4)
{
TL = p1;
TR = p2;
BR = p3;
BL = p4;
}

}
class Point
{
public double x;
public double y;
Point(double a, double b)
{
x = a;
y = b;
}

}
class trapezoid extends Quadrilateral
{
public trapezoid(Point p1, Point p2, Point p3, Point p4)
{
super(p1,p2,p3,p4);
}
public double areaofTrapezoid()
{
return ((((TR.x-TL.x)+(BR.x-BL.x))/2)*(TL.y-BL.y));
}
}

我正在尝试访问 TR、TL、BR 和 BL 中的 x 和 y 值,但我不想在四边形类中创建像 getxofTL、getyofTL、getxofBR... 等函数。在不更改变量的访问说明符的情况下,我还能如何访问子类中的这些值。

最佳答案

子类不能直接访问私有(private)成员(与 protected 成员相反)。因此,除非您想使用反射(您不应该!),否则您应该使用公共(public)/ protected 访问器。

除了创建 setter/getter 可能带来的潜在麻烦之外,我想不出任何理由为什么你不想要这样的 setter/getter 。请注意,大多数 IDE 可以自动为您执行此操作。

有关引用,请参阅Controlling Access to Members of a Class .

关于java - 私有(private)成员的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21716802/

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