近一个月由于项目所需软件需要,开始学习java .还好之前有些C++基础,学习来不算那么费劲。反而感觉JAVA比C++方便不少,现成的类、方法都可以用。但是今天遇到了一个问题:代码如下:
public class Math {
static class Test1 {
int i=0;
}
public static class Test{
//static Random rand = new Random();
private final int VALUE_1 = 9;
private static final int VALUE_2 = 10;
private final Test1 test1 = new Test1();
}
public static void main(String args[]) {
//out.print(max(1,4));
Test t1 = new Test();
//t1.i = 2;
//Test1 t2 = new Test();
//t1.VALUE_1 = 11;
//t1.test1 = new Test1();
out.print(t1.VALUE_1);
}
}
开始 Test t1 = new Test();报错:No enclosing instance of type Math is accessible. Must qualify the allocation with an enclosing instance of type Math(e.g. x.new A() where x is an instance ofMath).试了很多次,都不行。可是书上的确是这么写的。考虑到JAVA很多static和非static都不能互相调用。只能在Test上加上static,然后才不会报错。那么就意味着以后大部分都要设为static?
由于main函数必须指定为static,那么怎么调用非static函数呢?将其放在一个非static class中:
public class HeritTest {
public static void main(String args[]){
sub sub1 = new sub();
sub1.dd1();sub1.dd2();sub1.dd3();
parent par1 = sub1;
//par1.dd1();
par1.dd2();
//par1.dd3();
}
}
就可以调用了。
此外注意权限修饰符,private都invisible。