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.总结
构造方法使用的原则
对象实例化必须调用构造方法
每一个类必须有一个构造方法
匿名对象只开辟了堆内存的实例对象