1. 程式人生 > >面向對象之構造方法

面向對象之構造方法

面向對象 構造方法

1.1 構造方法:
主要用來給對象的數據進行初始化
1.1.1 構造方法格式:
A:構造方法格式
a:方法名與類名相同
b:沒有返回值類型,連void都沒有
c:沒有具體的返回值
1.1.1.1 案例代碼十一:

package com.itheima_08;
/*
 * 構造方法:
 * 給對象的數據進行初始化
 *
 * 格式:
 * 方法名和類名相同
 * 沒有返回值類型,連void都不能寫
 * 沒有具體的返回值
 *
 */
public class Student {
public Student() {
System.out.println("這是構造方法");
}
}
package com.itheima_08;

public class StudentDemo {
public static void main(String[] args) {
//如何調用構造方法呢?
//通過new關鍵字調用
//格式:類名 對象名 = new 構造方法(...);
Student s = new Student();
}
}

1.1.2 構造方法註意事項與重載
如果你不提供構造方法,系統會給出默認構造方法
如果你提供了構造方法,系統將不再提供
構造方法也是可以重載的,重載條件和普通方法相同
1.1.2.1 案例代碼十二:

package com.itheima_08;
/*
 * 構造方法:
 * 給對象的數據進行初始化
 *
 * 格式:
 * 方法名和類名相同
 * 沒有返回值類型,連void都不能寫
 * 沒有具體的返回值
 *
 * 構造方法的註意事項:
 * A:如果我們沒有給出構造方法,系統將會提供一個默認的無參構造方法供我們使用。
 * B:如果我們給出了構造方法,系統將不在提供默認的無參構造方法供我們使用。
 *        這個時候,如果我們想使用無參構造方法,就必須自己提供。
 *        推薦:自己給無參構造方法
 *      C:構造方法也是可以重載的
 *
 * 成員變量賦值:
 * A:setXxx()方法
 * B:帶參構造方法
 */
public class Student {
private String name;
private int age;
/*
public Student() {
System.out.println("這是構造方法");
}
*/
public Student() {}
public Student(String name) {
this.name = name;
}
public Student(int age) {
this.age = age;
}
public Student(String name,int age) {
this.name = name;
this.age = age;
}

public void show() {
System.out.println(name+"---"+age);
}
}
package com.itheima_08;

public class StudentDemo {
public static void main(String[] args) {
//如何調用構造方法呢?
//通過new關鍵字調用
//格式:類名 對象名 = new 構造方法(...);
Student s = new Student();
s.show();
//public Student(String name)
Student s2 = new Student("林青霞");
s2.show();
//public Student(int age)
Student s3 = new Student(28);
s3.show();
//public Student(String name,int age)
Student s4 = new Student("林青霞",28);
s4.show();
}
}

1.1.3 包含private,無參,有參構造的標準學生類代碼:
A:類:
a:成員變量
b:構造方法
無參構造方法
帶參構造方法
c:成員方法
getXxx()
setXxx()
B:給成員變量賦值的方式
a:無參構造方法+setXxx()
b:帶參構造方法
1.1.3.1 案例代碼十三:

package com.itheima_09;
/*
 * 學生類
 */
public class Student {
//成員變量
private String name;
private int age;
//構造方法
public Student() {}
public Student(String name,int age) {
this.name = name;
this.age = age;
}
//成員方法
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}
package com.itheima_09;
/*
 * 學生類的測試類
 */
public class StudentDemo {
public static void main(String[] args) {
//無參+setXxx()
Student s = new  Student();
s.setName("林青霞");
s.setAge(28);
System.out.println(s.getName()+"---"+s.getAge());
//帶參構造
Student s2 = new Student("林青霞",28);
System.out.println(s2.getName()+"---"+s2.getAge());
}
}

面向對象之構造方法