什么是构造方法?首先,我们来看看对象的产生格式:
类名称 对象名称=new 类名称()
我们都知道在java中()是表示一个方法,那么上面的类名称()就是一个构造方法。只要已有对象实例化就会调用构造方法。
构造方法必须遵循的几个原则:
- 构造方法的名称必须和类名称一致
- 构造方法的申明处不能有任何的返回值类型申明
- 不能再构造方法中使用return返回一个值
class Person{
public Person(){ // 声明构造方法
System.out.println("一个新的Person对象产生。") ;
}
};
public class ConsDemo01{
public static void main(String args[]){
System.out.println("声明对象:Person per = null ;") ;
Person per = null ; // 声明对象时并不去调用构造方法
System.out.println("实例化对象:per = new Person() ;") ;
per = new Person() ;//实例化对象
}
};
在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 ConsDemo02{
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() ;
}
};
注意: 如果一个类中明确地定义了一个构造方法,则不会再产生无参的什么都不做的构造方法,所以在实例化对象的时候一定要按照参数要求传入参数,使用per = new Person() 时会发生编译错误。
构造方法本身与普通方法一样,是可以重载的。
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() ;
}
};
匿名对象
匿名:没有名字,在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() ;//开辟堆内存空间,但是少了栈内存中的引用
}
};
所谓的匿名对象就是比之前的对象少了一个栈内存的引用关系,即只在堆内存中开辟空间,而不再栈内存中引用。