如何从抽象类访问函数而不将其设为静态?
我想创建一个只能继承的类,因为我知道它应该是抽象的。但现在的问题是我想使用该类的函数而不将它们设为静态。我该怎么办呢。
public abstract Class A
{
A()
{}
public void display()
{}
}
public Class B:A
{
base.A() // this is accessible
this.display() // this is not accessible if i dont make this function static above
}
I want to create a class that can only be inherited, for that i know it should be made abstract. But now the problem is that i want to use functions of that class without making them static. How can i do that.
public abstract Class A
{
A()
{}
public void display()
{}
}
public Class B:A
{
base.A() // this is accessible
this.display() // this is not accessible if i dont make this function static above
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的示例将无法编译,您可以考虑如下所示:
输出:
注意:创建新的 B() 隐式调用 A();我必须将 A 的构造函数设置为 protected 以防止出现此错误:
“‘AA()’由于其保护级别而无法访问”
Your example will not compile, you could consider something like this:
Output:
Note: Creating a new B() implicitly calls A(); I had to make the constructor of A protected to prevent this error:
"'A.A()' is inaccessible due to its protection level"
那不是真的。您不必将 Display() 设为静态;您可以从子类中自由调用它。另一方面,你不能像那样调用构造函数。
也许这只是示例中的一个错误,但您所拥有的代码的真正问题是您不能将方法调用放在类定义的中间。
试试这个:
That's not true. You don't have to make Display() static; you can call it freely from the subclass. On the other hand, you can't call the constructor like that.
Maybe it's just an error in the example, but the real issue with the code you have is that you can't put method calls in the middle of your class definition.
Try this:
这是你可以如何做到这一点..
Here's how you can do this..