Java构造函数的说明。

Java类的构造方法(constructor

1.构造函数名与类名相同

2.构造函数不返回任何值,也没有返回类型(包括void

3.每一个类可以有一个或多个构造方法;

4.构造方法在创建对象时自动执行,不用显式地直接调用。

实现形式:

1.系统默认的构造方法。

2.自定义构造方法与方法重载

3.自定义无参的构造方法

4.this

public class Person {
	private String name;
	private int age;
	public Person()	{
		System.out.println("this is a default constructor!");
	}  //default constructor
	public Person(String s)
	{
		name = s;// or using the key word -- this.
		//this.name = s; 
		System.out.println("this is a default constructor with one parameter!");
	}

	public Person(String s, int n)	{
		//name = s;
		this.name = s;
		//age = n;
		this.age = n;
		System.out.println("this is a default constructor with two parameter!");
	}
	
	public String talk()	{
		return "My name is "+name+", and age is "+age+".";
	}
}

public class TestConstruct
{
	public static void main(String[] args)
	{
		
		Person p1 = new Person();
		Person p3 = new Person("jiaojiao");
		Person p2 = new Person("Wenliang", 25);
		
		System.out.println(p1.talk());
		System.out.println(p2.talk());
		System.out.println(p3.talk());
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值