地球诞生怎么出现在第一个调用后面的,不知道为什么

地球诞生怎么出现在第一个调用后面的,不知道为什么

public class Earth {
     //定义私有构造方法,并在构造方法中打印输出“地球诞生”
	private Earth(){
	    System.out.println("地球诞生");
	} 
	 //定义私有静态类对象并完成实例化
		private static Earth earth=new Earth();
	 //定义公有静态方法返回类内的私有静态对象
	public static Earth getEarth(){
	    return earth;
	}
} 
public class Test {

    public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("第一个地球创建中。。。。");
        Earth one=Earth.getEarth();
		System.out.println("第二个地球创建中。。。。");
	    
		Earth two=Earth.getEarth();
		
		System.out.println("第三个地球创建中。。。。");
		Earth three=Earth.getEarth();
		System.out.println("问:三个地球是同一个么?");
		System.out.println(one);
		System.out.println(two);
		System.out.println(three);
	}
}


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

2回答
Tender10 2017-07-12 09:44:15
public class Earth {
    //定义私有构造方法,并在构造方法中打印输出“地球诞生”
    private Earth(){
        System.out.println("地球诞生");
    } 
    //定义私有静态类对象并完成实例化
    private static Earth earth=new Earth();
    //定义公有静态方法返回类内的私有静态对象
    public static Earth getEarth(){
        return earth;
    }
}

上述代码中,因为在类中已经完成了Earth类对象的初始化new Earth(),已经将"地球诞生"赋值给了Earth
,所以在Test类中Earth创建一个对象one,并且调用getEarth()方法去获取值,而获取到的值就是"地球诞生"。

Tender10 2017-07-11 10:08:34

首先main方法输出“第一个地球创建中。。。。”,然后实例化了一个地球对象one,并且Earth,调用getEarth()方法,获取得到的返回值是”地球诞生“,并且做了输出。

  • 提问者 慕后端3163330 #1
    getearth方法怎么会输出构造方法的内容,不是很懂
    2017-07-12 08:37:42
  • 被鱼迷死的海 回复 提问者 慕后端3163330 #2
    getearth 返回的是你构造好的earth对象,而这个对象需要进行创建,在创建的过程中就会调用构造方法,构造方法中的内容就会自然而然地输出
    2017-07-20 15:23:37
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师