1.This關鍵字:
代表所在類的對象引用
記住:方法被哪個對象調用,this就代表哪個對象。
什麼時候用this呢?
局部變量隱藏成員變量
package yang1;
//get獲取值需要返回,set都要傳參
class Phone{
private String lable;
private int price;
private String color;
public String getLable() {
return lable;
}
public void setLable(String lable){
this.lable=lable;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price =price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color=color;
}
}
class PhoneTest {
public static void main(String[] args) {
Phone p=new Phone();
p.setLable("小米");
p.setPrice(2000);
p.setColor("白");
System.out.println(p.getLable()+"-----"+p.getPrice()+"---"+p.getColor());
}
}
2.構造方法:
有括號的叫變量,沒有括號的叫方法;
構造方法作用概述:給對象的數據進行初始化;
構造方法格式:
1 方法名與類名相同;
2. 沒有返回值類型,連void都沒有;
3. 沒有具體的返回值;
注意事項:
(1)如果不提供構造方法,系統會給出默認構造方法;
(2)只要我們給出了構造方法,不管帶參還是無參,系統都不再提供無參構造方法;
(3)構造方法也是可以重載的;
(4)給成員變量賦值有2種方法。
構造方法的重載格式,方法名相同,類型名不同
1. setXxx
2. 2.構造方法
3. class Student{
4. private String name;
5. private int age;
6. public Student() {
7. System.out.println("愛你");
8. }
9.
10. //構造方法的重載格式,方法名相同,類型名不同
11. //這是一個帶多個參數的構造方法
12. public Student(String name,int age) {
13. this.name=name;
14. this.age=age;
15. }
16.
17. public void show() {
18. System.out.println(name+"---"+age);
19. }
20. }
21.
22. public class ConstructDemo {
23. public static void main(String[] args) {
24. //創建對象
25. Student s =new Student("範範",20);
26. s.show();
}
}
3.類的組成:成員變量,成員方法
以後再提類的組成:
(1)成員變量
(2)構造方法
(3)成員方法
方法具體劃分:
(1)根據返回值:有明確的返回值
(2)返回void類型的方法
根據形式參數:
(1)無參方法
(2)帶參方法
class Student{
public String getString() {
return "fanfan";
}
public void show() {
System.out.println("show");
}
public void method(String name) {
System.out.println(name);
}
public String function(String s1,String s2) {
return s1+s2;
}
}
public class StudentDemo {
public static void main(String args[]) {
Student s=new Student();
//調用無參無返回值方法
s.show();
//調用無參有返回值方法
String result=s.getString();
System.out.println(result);
//調用帶參無返回值的的方法
s.method("範範");
String result2=s.function("fanfan","2ge");
System.out.println(result2);
}