java的构造方法

引用:https://blog.csdn.net/zw1996/article/details/52878270
constructor:构造方法
new对象时,都是用构造方法进行实例化的;例如 Animal animal =new Animal();
1\构造方法的方法名必须与类名一样。
2\构造方法没有返回值,不能用void,在方法名前面不能声明方法类型。
3\可以进行重载

单个构造方法
    public class Dog {

	private String color;
	private int height;
    public Dog() {
        this.color=“red”;
        this.height=12;
        
       }
    
    public int getHeight() {
		return height;
	}
	public String getColor() {
		return color;
	  }
    }

public class Dog_constructor {

	public static void main(String[] args) {
		Dog d=new Dog();
		System.out.println("狗的颜色:"+d.getColor());
		System.out.println("狗的大小:"+d.getHeight());
	}
}

上面的代码的包名没复制。

多个构造方法:
public class Dog {

	private String color;
	private int height;
    public Dog() {
        this.color="red";
        this.height=12; 
       }
    public Dog(String c,int h) {
    	
    	this.color=c;
    	this.height=h;
    }
    
    public int getHeight() {
		return height;
	}
	public String getColor() {
		return color;
	  }
    }

public class Dog_constructor {

	public static void main(String[] args) {
		Dog d=new Dog();
		Dog d1=new Dog();
		System.out.println("无参构造方法");
		System.out.println("狗的颜色:"+d.getColor());
		System.out.println("狗的大小:"+d.getHeight());
		System.out.println("有参构造方法");
		System.out.println("狗的颜色:"+d1.getColor());
		System.out.println("狗的大小:"+d1.getHeight());
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值