这个程序是类的对象引用变量的演示
class Super1
{
final int num1=22;
final int num2=10;
}
class add extends Super1
{
add()
{
System.out.println("object of class add created");
}
void result()
{
System.out.println("The additon of two numbers: "+(num1+num2));
}
protected void finalize()
{
System.out.println("Object of class add Destroyed");
}
}
class sub extends Super1
{
sub()
{
System.out.println("class sub object created");
}
void result()
{
System.out.println("The sustraction of two numbers is"+(num1-num2));
}
protected void finalize()
{
System.out.println("Sub class object destroyed");
}
}
class i111
{
public static void main(String args[])
{
Super1 ref;
add obj1=new add();
sub obj2=new sub();
ref=obj1;
ref.result();
obj1=null;
ref=obj2;
ref.result();
obj2=null;
}
}
编译后我得到了
错误: 找不到符号 ref.result(); symbol: 方法 result()
位置:超级1类型的变量参考
你声明了一个变量 ref,类型为 Super1
:
Super1 ref;
您尝试在此变量上调用方法 result()
:
ref.result();
但Super1被定义为
class Super1 {
final int num1=22;
final int num2=10;
}
所以它没有任何result()
方法,因此错误。