Java基礎002
阿新 • • 發佈:2018-11-13
目錄
給類屬性賦值的方式
直接在類裡面賦值
public class Student {
String name = "張君瑞";
int age = 23;
String sex = "男";
String address = "陽泉平定";
void sayHi() {
System.out.println("我叫" + name + ",我今年" + age + "歲了");
}
}
這樣做,每個物件出來後都長得一模一樣
public class Test {
public static void main(String[] args) { //程式的主入口
Student stu = new Student();
Student stu2 = new Student();
Student stu3 = new Student();
}
}
在程式賦值
public class Student{
String name;
int age;
String sex;
String address;
void sayHi() {
System.out.println("我叫" + name + ",我今年" + age + "歲了");
}
}
這樣做太麻煩
public class Test {
public static void main(String[] args) { //程式的主入口
Student s1 = new Student();
s1.name = "zjr";
s1.age = 23;
s1.sex = "男";
s1.address = "陽泉平定巨城連莊";
s1.sayHi();
Student s2 = new Student();
s2.name = "cxl";
s2.age = 23;
s2.sex = "女";
s2.address = "臨汾霍州";
s2.sayHi();
Student s3 = new Student();
s3.name = "ww";
s3.age = 24;
s3.sex = "男";
s3.address = "陽泉平定巨城連莊";
s3.sayHi();
Student s4 = new Student();
s4.name = "wsj";
s4.age = 24;
s4.sex = "男";
s4.address = "晉城陽城";
s4.sayHi();
}
}
通過構造器賦值(提倡)
public class Student{
String name;
int age;
String sex;
String address;
Student(String name,int age,String sex,String address) { //構造器 this指代當前類物件
this.name = name;
this.age = age;
this.sex = sex;
this.address = address;
}
void sayHi() {
System.out.println("我叫" + name + ",我今年" + age + "歲了");
}
}
這種方式是提倡的,這樣做就很不錯,程式碼量少,還很清晰,不容易出錯
public class Test {
public static void main(String[] args) { //程式的主入口
Student s1 = new Student("張君瑞",23,"男","平定連莊");
s1.sayHi();
Student s2 = new Student("成小麗",23,"女","臨汾霍州");
s2.sayHi();
Student s3 = new Student("王偉",23,"男","平定連莊");
s3.sayHi();
Student s4 = new Student("王世傑",23,"男","晉城陽城");
s4.sayHi();
}
}
過載
解釋: 方法名相同,引數列表不同(個數,型別,位置)
public class Aoo{
void say(){}
void say(String name){}
void say(String name,int age){}
void say(int age, String name){}
void say(int num){}
}
構造方法是可以過載的,目的是去創造不同的物件,符合更多要求的物件
public class Aoo {
Aoo() {} //無參構造 系統預設提供,如果我們提供了構造方法,系統就不提供了,如果還想要無參的,就得自己寫
Aoo(String name, int age) {
this.name = name;
this.age = age;
}
Aoo(String name) {
this.name = name;
}
Aoo(int age) {
this("張君瑞",age); //通過過載呼叫引數多的構造,進行屬性賦值
}
}
NULL
空: 是針對引用的,如果引用為空,表示不能使用物件了,如果使用物件就會報NullPointerException異常。
public class Aoo {
String name;
void sayHi(){}
public static void main(String[] args) {
Aoo aoo = new Aoo();
aoo.name = "zjr";
aoo.sayHi();
aoo = null;
aoo.sayHi(); //報錯 因為aoo已經為空了,不在aoo不再指向任何物件
}
}