赖振军 发表于 2017-7-4 15:02:51

java-抽象类遇到的问题

package com.test.jun;
import com.test.jun.A.B;
abstract class A {
    public static final String FLAG = "CHINA";
    private String name = "june";   
    public void setName(String name) {
this.name = name;
}
    public String getName() {
return name;
}
    public abstract void print();
public static class B extends A{
public void print() {
// TODO Auto-generated method stub
System.out.println("FLAG:" + FLAG);
System.out.println("name:" +super.getName());
}
    }
}

public class AbstractTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub//抽象类不能初始化,所以new A 是错误的//A a=new A();
B b= new B();
b.print();
}
}-------------------------------------------------------------------------------------------- class B extends A{   public void print() {
   // TODO Auto-generated method stub
   System.out.println("FLAG:" + FLAG);
   System.out.println("name:" +super.getName());
   }
    }
//抽象类无法初始化的,需要初始化就别用抽象类,用抽象类的子类,当时new B时候还是报错。错误为:No enclosing instance of type A is accessible. Must qualify the allocation with an enclosing instance of type A (e.g. x.new A() where x is an instance of A).然后一直纳闷,不是说抽象类不能初始化,可以用抽象类的子类吗?然后百度一下。答案是:我写的内部类是动态的,也就是开头以public class开头。而主程序是public static class main解决方法为: class B extends A{   改为 public static class B extends A{public static class B extends A{   public void print() {
   // TODO Auto-generated method stub
   System.out.println("FLAG:" + FLAG);
   System.out.println("name:" +super.getName());
   }
    }

yzt2017 发表于 2017-10-17 10:13:09

谢谢楼主分享!楼主辛苦了!
页: [1]
查看完整版本: java-抽象类遇到的问题