重写java中的方法约束

发布于 2024-12-03 11:06:30 字数 1287 浏览 3 评论 0原文

java中的重写方法具有以下特点:

1> Overrinding 方法应具有与父类方法相同的参数列表。

2>返回类型应该与父类方法的返回类型相同/子类。

3>访问级别应与父类方法相同或限制较少。

4>重写的方法可以抛出相同或较窄的异常,而不是更宽的异常。

*只是想知道为什么点会这样*

*2 - 为什么子类为什么不是超类?*

3 - 为什么访问级别应该减少限制?

4 - 为什么它应该抛出窄异常?

根据我的理解,这只是如果我正在创建父类引用创建一个子类对象并尝试运行每个场景然后

让我们假设A是父类B是子类都具有方法printAndReturnSomething()

public class A{

       public B printAndReturnSomething(){
                S.O.P("Inside A Print");
                return new B();
              }
}

现在我们有子类B

public class B extends A{
       public A printAndReturnSomething(){ // I know this isn't possible to return A but had it been then
                S.O.P("Inside A Print");
                return new A();
              }
}

现在如果我做某事像这样

A a =new B();

,现在因为我有 A 的引用,所以我希望返回类型为 B 类型

B returnedValue=a.printAndReturnSomething(); // But it actually calls the child class method and hence returns A. So here comes the contradiction.

,与场景 3 和 4 类似。我的理解正确吗?我还缺少其他更相关的东西吗?

Overriding Methods in java have the following features :

1> The Overrinding method should have the same argument list as the Parent class method.

2> The return type should be the same/subclass of the return type for the parent class method.

3> The access level should be same or less restrictive as the parent class method.

4> The overriden method can throw the same or Narrower exception and not a broader one.

*Just wanted to know why is it so for point *

*2 - why subclass why not a superclass?*

3 - why the access level should be less restrictive?

4 - why it should throw narrow exception?

As per my understanding its just that if i am creating a parent class refrence to create a child class object and trying to run down each of the scenario then

Lets assume A is parent class and B is child class both having method printAndReturnSomething()

public class A{

       public B printAndReturnSomething(){
                S.O.P("Inside A Print");
                return new B();
              }
}

Now we have the child class B as

public class B extends A{
       public A printAndReturnSomething(){ // I know this isn't possible to return A but had it been then
                S.O.P("Inside A Print");
                return new A();
              }
}

Now if i do something like this

A a =new B();

and now as i have a reference of A so i expect the return type to be of type B

B returnedValue=a.printAndReturnSomething(); // But it actually calls the child class method and hence returns A. So here comes the contradiction.

Similaraly for the scenarios 3 and 4. Is my understanding correct? Am i missing something else more relevant?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

披肩女神 2024-12-10 11:06:30

所有这些都可以用“子类必须表现得像超类一样”来概括。因此,如果 Derived 扩展 Base 并且我有一个 Derived 类型的对象 x,那么我希望它的行为准确就像它是Base类型一样。

因此,如果 x.foo() 返回某种类型 T,并且 Base::foo() 返回类型 S >,那么我希望能够将 x.foo() 视为 S,因此 T 最好与其相同或子类S

同样,x.foo() 应该只抛出 Base:foo() 承诺的异常。它无法开始抛出新的、意外的异常。

如果 Base::foo() 是公共的,那么 x.foo() 也应该是公共的。你不能突然对派生类有更严格的限制,因为基类向我保证它是公共的。

始终将继承视为“表现得像超类”,或者“可以像超类一样对待”,这一切都应该清楚。

All of this can be summarized by saying that "a subclass has to behave as if it was a superclass". So if Derived extends Base and I have an object x of type Derived, then I want it to behave exactly as if it were of type Base.

So if x.foo() returns some type T, and Base::foo() returns a type S, then I want to be able to treat x.foo() as an S, so T better be the same as or a subclass of S.

Similarly, x.foo() should only throw exceptions that Base:foo() promises. It can't start throwing new, unexpected exceptions.

If Base::foo() is public, then so should x.foo() be. You can't suddenly have a tighter restriction on the derived class, because the base class promised me that it was public.

Always think of inheritance as "behaves like the super class", or "can be treated like the superclass", and all this should be clear.

泪冰清 2024-12-10 11:06:30

根据我的理解,如果我创建一个父类引用来创建一个子类对象并尝试运行每个场景......

我认为您正确理解了这个想法。

父类引用子类对象的情况就是所谓的里氏替换原则发挥作用:在计算机程序中,如果 S 是 T 的子类型,则 T 类型的对象 [即您的“父类”] 可以替换为 S 类型的对象 > [那是你的“子类对象”](即,S 类型的对象可以替代 T 类型的对象),而不改变该程序的任何所需属性(正确性、执行的任务等)。 .

As per my understanding its just that if i am creating a parent class refrence to create a child class object and trying to run down each of the scenario...

I think you groked the idea correctly.

Case with parent class referencing subclass object is where so called Liskov substitution principle comes into play: in a computer program if S is a subtype of T, then objects of type T [that's your "parent class"] may be replaced with objects of type S [that's your "child class object"] (i.e., objects of type S may be substitutes for objects of type T), without altering any of the desirable properties of that program (correctness, task performed, etc.)...

毅然前行 2024-12-10 11:06:30

第 2 点

想象一下:

class Animal {}
class Dog extends Animal {}

class Base {
    Dog get() { ... }
}

class Derived extends Base {
    Animal get() { ... }
}

Base b = new Derived();
Dog d = b.get(); // What?

类似的逻辑可以应用于其他问题。

Point #2

Imagine the following:

class Animal {}
class Dog extends Animal {}

class Base {
    Dog get() { ... }
}

class Derived extends Base {
    Animal get() { ... }
}

Base b = new Derived();
Dog d = b.get(); // What?

Similar logic can be applied to the other questions.

少钕鈤記 2024-12-10 11:06:30

回答你的观点:

2 - 为什么子类为什么不是超类?

如果允许超类,可能会发生这种情况:

class A {
    public A makeCopy() { return clone(); }
}

class B extends A {
    public Object makeCopy() { return new Date(); }
}

public static void main(String[] args) {
    A a = new B();
    A copy = a.makeCopy(); // OOPS -- didn't get an A after all!
}

3 - 为什么访问级别应该减少限制?

修改上面的 B 类:

class B extends A {
    private A makeCopy() { return clone(); }
}

public static void main(String[] args) {
    A a = new B();
    A copy = a.makeCopy(); // OOPS -- accessing a private method!
}

4 - 为什么它应该抛出窄异常?

同样的想法 - 如果 A.makeCopy 被声明为抛出 AException (假设的异常类声明于A),但是 B.makeCopy 被声明为抛出 Throwable,那么 B.makeCopy 可以抛出任何东西。这将导致无法在 main 中合理地编写 ​​try/catch 块。

To answer your points:

2 - why subclass why not a superclass?

If a superclass were allowed, this could happen:

class A {
    public A makeCopy() { return clone(); }
}

class B extends A {
    public Object makeCopy() { return new Date(); }
}

public static void main(String[] args) {
    A a = new B();
    A copy = a.makeCopy(); // OOPS -- didn't get an A after all!
}

3 - why the access level should be less restrictive?

Modify the above B class to:

class B extends A {
    private A makeCopy() { return clone(); }
}

public static void main(String[] args) {
    A a = new B();
    A copy = a.makeCopy(); // OOPS -- accessing a private method!
}

4 - why it should throw narrow exception?

Same idea -- if A.makeCopy was declared to throw an AException (a hypothetical exception class declared in A), but B.makeCopy was declared to throw Throwable, then B.makeCopy could throw just about anything. That would make it impossible to rationally code a try/catch block in main.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文