搜索
 找回密码
 立即注册

简单一步 , 微信登陆

java-抽象类遇到的问题

作者:赖振军 | 时间:2017-7-4 15:02:51 | 阅读:4901| 只看该作者
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());
   }
    }


收藏
收藏0
分享
分享
点赞
点赞0
反对
反对0
回复

使用道具 举报

大神点评1

沙发#
yzt2017 发表于:2017-10-17 10:13:09
谢谢楼主分享!楼主辛苦了!
[url=http://www.yunzhitu.com ]云智图[/ur
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册
手机版