Java中的OOP:带方法链接的类继承 [英] OOP in Java: Class inheritance with method chaining

查看:50
本文介绍了Java中的OOP:带方法链接的类继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父类,它定义了链接器方法的集合(返回"this"的方法).我想定义多个子类,这些子类包含它们自己的链接器方法,但也覆盖"父方法,以便返回子类的实例而不是父类.

I have a parent class, which defines a collection of chainer methods (methods that return "this"). I want to define multiple child classes that contain their own chainer methods but that also "override" the parent methods so that an instance of the child class is returned instead of the parent class.

我不想在每个子类中都重复相同的方法,这就是为什么我有一个父类包含所有子类共享的方法的原因.谢谢.

I don't want to have to repeat the same methods in each child class, which is why I have a parent class that contains the methods that all the child classes share. Thanks.

class Chain {
  public Chain foo(String s){
    ...
    return this;
  }
}

class ChainChild extends Chain {
  //I don't want to add a "foo" method to each child class
  /*
  public ChildChain foo(String s){
    ...
    return this;
  }
  */

  public ChainChild bar(boolean b){
    ...
    return this;
  }
}

ChainChild child = new ChainChild();
child.foo().bar(); //compile error: foo() returns a "Chain" object which does not define the bar() method. 

推荐答案

父类中返回this的方法仍将返回对子类对象的引用.您只能将其视为父类的对象(除非您对其进行了强制转换),但实际上它将是其原始类型.

A method in the parent class that returns this will still return a reference to the object of the child class. You will only be able to treat it as an object of the parent class (unless you cast it) but it will actually be of its original type.

您可以考虑使用这样的泛型:

You could consider using generics like this:

// This seems a bit too contrived for my liking. Perhaps someone else will have a better idea.
public class Parent<T extends Parent<T>> {
    T foo () {
        return (T) this;
    }
}

public class Child extends Parent<Child> {
    public void bar () {
        Child c = foo();
    }
}

这篇关于Java中的OOP:带方法链接的类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆