[英]Why this difference in creating reference type object of an abstract class and accessing its own members?
Consider i have an abstract class with a non-abstract method in it. 考虑我有一个抽象类,其中包含非抽象方法。 i tried creating reference type object and access that non-abstract method.. it gives me a compilation error.
我尝试创建引用类型对象并访问非抽象方法..它给我一个编译错误。 The following program demonstrates it.
以下程序演示了它。
abstract class A
{
public void print()
{
System.out.println("this is the print method");
}
}
class test
{
public static void main(String args[])
{
A ob;
ob.print();
}
}
then this is the output i am getting, 那么这就是我得到的输出,
Variable ob might not have been initialized
变量ob可能尚未初始化
If i assume the above as true, then why is it allowing the same in the following program. 如果我假设上述为真,那么为什么在以下程序中允许相同的内容。 In the following Applet, i use the
paint()
method as an entry point. 在下面的Applet中,我使用
paint()
方法作为入口点。 So, here i create a reference type object of predefined class Graphics
(an abstract class), and try accessing the drawString()
method of it, then no compilation error.. like this--> 所以,在这里我创建一个预定义类
Graphics
(一个抽象类)的引用类型对象,并尝试访问它的drawString()
方法,然后没有编译错误..像这样 - >
import java.applet.*;
import java.awt.*;
public class apptest extends Applet
{
public void paint(Graphics g)// Graphics is an abstract class
{
String s="this is an applet";
g.drawString(s,20,20);
}
}
How is this Applet allowing me to do the same ? 这个小程序如何允许我这样做?
You have understood it wrong, in the below code Graphics
is a parameter to a method, even though its an abstract class 你已经理解错了,在下面的代码中,
Graphics
是一个方法的参数,即使它是一个抽象类
public void paint(Graphics g)// Graphics is an abstract class
{
String s="this is an applet";
g.drawString(s,20,20);
}
To invoke this method, the caller should definitely create a concrete instance of type Graphics
. 要调用此方法,调用者应该创建一个
Graphics
类型的具体实例。 Something like below 像下面的东西
Graphics g = new TwoDGraphics(); // TwoDGraphics extends Graphics, and a non abstract class
applet.paint(g);
Coming back to your example.. its an error to use an uninitialized variable 回到你的例子..使用未初始化的变量是一个错误
A ob; --> its not initialized
ob.print();
a below code should have worked. 下面的代码应该有效。
A ob = new A() {
//created an anonymous implementation of abstract A
}
ob.print();
Two things: 两件事情:
So in short you will not be able to achieve what you are trying to do. 所以简而言之,你将无法实现你想要做的事情。 There two ways to call the non-abstract method of an abstrac class:
有两种方法可以调用abstrac类的非抽象方法:
Create a child class and using its object you can call the non-abstract method of your abstract class. 创建子类并使用其对象可以调用抽象类的非抽象方法。 You may use the reference of either your child class or your parent class, if you have not overridden the method, then call to non-abstract method will always call the parent class method.
您可以使用您的子类或您的父类的引用,如果您没有重写该方法,则调用非抽象方法将始终调用父类方法。
Make the method static and call it using the reference of parent clas. 使方法静态并使用parent clas的引用来调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.