gpt4 book ai didi

java - 为什么子类的方法可以更容易访问?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:08 25 4
gpt4 key购买 nike

一个简单的例子

class A {
protected int foo(int x){
return x;
}
}

class B extends A {
public int foo(int x){
return x*x;
}
}

这在 Java 中是允许的,并且可以毫无问题地工作。但是假设你在另一个包中声明了

A b = new B();
int z = b.foo(5);

那么这将不起作用,因为显然 A foo() 是 protected 。但是,为什么首先要允许子类中有更多可访问的方法呢?这在某些情况下有用吗?

最佳答案

一般来说,子类可以在继承自父类的接口(interface)中添加方法。使方法更易于访问是有效地添加到接口(interface)。

But then why allow in the first place to have more accessible methods in the subclasses?

因为它对于包含子类引用的代码很有用。

Is there a case where this is helpful?

一个很好的例子是 Object.clone(),一种 protected 方法。所有 Java 类都是 Object 的直接或间接子类。支持克隆的子类可以选择公开这个方法。

Foo foo1 = new Foo();
Foo foo2 = foo1.clone(); // Sometimes you're holding a subclass reference.

关于java - 为什么子类的方法可以更容易访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52670624/

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