Java引用变量 - 未找到符号

时间:2015-03-08 09:50:53

标签: java variables reference

该程序演示了类

的对象引用变量
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();符号:方法结果()
  location:Super1类型的变量ref

1 个答案:

答案 0 :(得分:1)

您声明类型为Super1的变量ref:

Super1 ref;

您尝试在此变量上调用方法result()

ref.result();

但Super1被定义为

class Super1 {
    final int num1=22;
    final int num2=10;
}

所以它没有任何result()方法,因此错误。