现在的位置: 首页 > 综合 > 正文

Java编译错误“No enclosing instance of type AA is accessible. Must qualify the allocation with an enclosing instance of type SimpleT

2013年06月21日 ⁄ 综合 ⁄ 共 696字 ⁄ 字号 评论关闭

package com.ncut;

public class ReferencePass {
 
 public static void main(String[] args) {
  
  Tree tree =new Tree(10);
  System.out.println("调用pass方法前:");
  System.out.println(tree);
  pass(tree);
  System.out.println("调用pass方法后:");
  System.out.println(tree);
 }
 public static void pass(Tree t) {
  t=new Tree(30);
  System.out.println("调用pass方法中:");
  System.out.println(t);
 }
  class Tree{
  private int height;
  public Tree(int h) {
      height=h;
  }
  public String toString() {
   
   return "树高"+height+"米";
  }
  
 }

}

 

这是因为AA是一个动态的内部类,创建这样的对象必须有实例与之对应,程序是在静态方法中直接调用动态内部类会报这样错误。   这样的错误好比类中的静态方法不能直接调用动态方法。可以把该内部类声明为static。或者不要在静态方法中调用。

那么为啥非静态方法不能调用动态方法呢,从面向对象的角度来说,动态方法与对象是联系密切的,比如发动是一个方法,它与汽车这个对象是关联的,所以只有new了汽车这个对象才能执行汽车.发动

static class Tree

抱歉!评论已关闭.