java 学习记录1

近一个月由于项目所需软件需要,开始学习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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值