java基础之构造方法

记住一句话:一旦有对象实例化就会调用构造方法



 构造方法的名称必须与类名称一样
 构造方法的声明不能有任何返回值类型的声明
 不能在构造方法中使用return返回一个值


每当创建一个类 默认创建一个无参的构造方法

写一个带有参数的构造方法


package KownClass;

class Person{
	private String name ;
	private int age ;
	public Person(String n,int a){		
<span style="white-space:pre">	</span>// 声明构造方法,为类中的属性初始化
		this.setName(n) ;
		this.setAge(a) ;
	}
	public void setName(String n){
		name = n ;
	}
	public void setAge(int a){
		if(a>0&&a<150){
			age = a ;
		}
	}
	public String getName(){
		return name ;
	}
	public int getAge(){
		return age ;
	}
	public void tell(){
		System.out.println("姓名:" + this.getName() + ";年龄:" + this.getAge()) ;
	}
};
public class test1{
	public static void main(String args[]){
		System.out.println("声明对象:Person per = null ;") ;
		Person per =  new Person("张三",30) ;//实例化对象
	
		per.tell() ;
	}
};

2.构造方法的重载


构造方法的重载和普通方法一样只要参数类型以及参数个数不同就可以完成重载

<span style="font-size:18px;">class Person{
	private String name ;
	private int age ;
	public Person(){}					// 声明一个无参的构造方法
	public Person(String n){			// 声明有一个参数的构造方法
		this.setName(n) ;
	}
	public Person(String n,int a){		// 声明构造方法,为类中的属性初始化
		this.setName(n) ;
		this.setAge(a) ;
	}
	public void setName(String n){
		name = n ;
	}
	public void setAge(int a){
		if(a>0&&a<150){
			age = a ;
		}
	}
	public String getName(){
		return name ;
	}
	public int getAge(){
		return age ;
	}
	public void tell(){
		System.out.println("姓名:" + this.getName() + ";年龄:" + this.getAge()) ;
	}
};
public class ConsDemo03{
	public static void main(String args[]){
		System.out.println("声明对象:Person per = null ;") ;
		Person per = null ;	// 声明对象时并不去调用构造方法
		System.out.println("实例化对象:per = new Person() ;") ;
		per = new Person("张三",30) ;//实例化对象
		per.tell() ;
	}
};</span>

3.3 匿名对象

匿名没有名字,在java中如果一个对象只使用一次,就可以定义成匿名对象

class Person{
	private String name ;
	private int age ;
	public Person(String n,int a){	// 声明构造方法,为类中的属性初始化
		this.setName(n) ;
		this.setAge(a) ;
	}
	public void setName(String n){
		name = n ;
	}
	public void setAge(int a){
		if(a>0&&a<150){
			age = a ;
		}
	}
	public String getName(){
		return name ;
	}
	public int getAge(){
		return age ;
	}
	public void tell(){
		System.out.println("姓名:" + this.getName() + ";年龄:" + this.getAge()) ;
	}
};
public class NonameDemo01{
	public static void main(String args[]){
		new Person("张三",30).tell() ;
	}
};
所谓匿名对象就是少了一个栈内存引用关系


4.总结

构造方法使用的原则

对象实例化必须调用构造方法

每一个类必须有一个构造方法

匿名对象只开辟了堆内存的实例对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值