第六周java课后报告

1,运行以下代码,得出结果

public class ceshi {
public static void main(String[]args) {
    Foo obj1=new Foo();
    Foo obj2=new Foo();
    System.out.println(obj1==obj2);
}
}
class Foo{
    int value=100;
}

 该等号比较的并不是两变量值,而是两变量的地址,所以得不出正确的结果。

2 运行以下代码,请问错误原因

我们易得,该类已经进行了初始化,在主函数中再进行初始化所以会进行报错。

3,类的初始化规则

当出现定义初始化,初始化模块,初始化类时,一切以顺序为准,即谁最后初始化,谁做主,

即覆盖准则。

4

package teacher;

class Root
{
    static{
        System.out.println("Root的静态初始化块");
    }
    {
        System.out.println("Root的普通初始化块");
    }
    public Root()
    {
        System.out.println("Root的无参数的构造器");
    }
}
class Mid extends Root
{
    static{
        System.out.println("Mid的静态初始化块");
    }
    {
        System.out.println("Mid的普通初始化块");
    }
    public Mid()
    {
        System.out.println("Mid的无参数的构造器");
    }
    public Mid(String msg)
    {
        //通过this调用同一类中重载的构造器
        this();
        System.out.println("Mid的带参数构造器,其参数值:" + msg);
    }
}
class Leaf extends Mid
{
    static{
        System.out.println("Leaf的静态初始化块");
    }
    {
        System.out.println("Leaf的普通初始化块");
    }    
    public Leaf()
    {
        //通过super调用父类中有一个字符串参数的构造器
        super("Java初始化顺序演示");
        System.out.println("执行Leaf的构造器");
    }

}

public class ceshi
{
    public static void main(String[] args) 
    {
        new Leaf();
        

    }
}

运行结果如下

猜你喜欢

转载自www.cnblogs.com/520520520zl/p/11695026.html