gpt4 book ai didi

java - 如何从子类的抽象父类 Java 8 访问子类的公共(public)方法

转载 作者:行者123 更新时间:2023-11-30 06:13:58 25 4
gpt4 key购买 nike

这个问题有点令人困惑,同时又很简单,但我无法找到解决方案。我会尽力表达清楚。

如何调用抽象父类(super class)的子类的公共(public)方法?

示例:

public abstract class SuperClass extends SomethingElse implements SomeOtherThing {
protected final PlmlForm plForm;

String getData() {
}
}

public class SubClass extends SuperClass {
private Report report;

String getReport() {
}
}

main(String[] args) {
SuperClass s = something();
}

我怎样才能做类似s.getReport()的事情?

是的,您可以调用抽象类。

最佳答案

您必须创建一个 SubClass public 类型的对象,以便可以从 SuperClass 访问实例 SubClass

public abstract class SuperClass extends SomethingElse implements SomeOtherThing {
protected final PlmlForm plForm = null;

String getData() { }

// How can I do something like s.getReport()?
// This is the way you call getReport
String getReport()
{
return new SubClass().s.getReport();

//If s is static...
return SubClass.s.getReport();
}

//Illustrative example
Subclass sub = new SubClass();
sub.s.getReport(); // Here the magic happens
}

public class SubClass extends SuperClass {
private Report report = null;

/*
* You create the object s that refers to Subclass
*/
public SuperClass/SubClass s = this;
//Or
public static SuperClass/SubClass s = this;
/********************************************/

String getReport() { }
}

main(String[] args) {
SuperClass s = this; // As SubClass extends from Superclass, for Java, it is the same as Superclass
SubClass s = this; // And here it is the same, since SubClass and SuperClass in this case are the same
}

关于java - 如何从子类的抽象父类 Java 8 访问子类的公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49641338/

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