java-抽象类

来源:互联网 发布:淘宝开店身份证照片图 编辑:程序博客网 时间:2024/05/17 18:45
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());
   }
    }