成員變量:Name,age
構造方法:初始化
無參,帶兩個參
成員方法
getXxx()/setXxx()
show();輸出該類的所有成員變量值
給成員變量賦值:
1.setXxx()方法
2.構造方法
輸出成員變量值的方式:
- 通過getXxx()分別獲取然後拼接
- 通過調用show()方法搞定
3. class Student{
4. private String name;
5. private int age;
6. public Student() {
7.
8. }
9. public Student(String name,int age) {
10. this.name=name;
11. this.age=age;
12. }
13. public String getName() {
14. return name;
15. }
16. public void setName(String name) {
17. this.name=name;
18. }
19. public int getAge(){
20. return age;
21. }
22. public void setAge(int age) {
23. this.age=age;
24. }
25. public void show() {
26. System.out.println(name+"-----"+age);
27. }
28. }
29. public class StudentTest {
30.
31. public static void main(String[] args) {
32. //方式1 給成員變量賦值
33. //無參構造+ssetXxx()
34. Student s=new Student();//先創建對象
35. s.setAge(24);
36. s.setName("加油");
37. System.out.println(s.getAge()+"---"+s.getName());
38. s.show();
39. //方式2給成員變量賦值
40. //直接賦值
41. Student s2=new Student("jia",24);
42. System.out.println(s2.getAge()+"---"+s2.getName());
}
}
一個標準的手機類代碼
class Phone{
private String brand;
private int price;
private String color;
public Phone() {
}
public Phone(String brand,int price,String color) {
this.brand=brand;
this.color=color;
this.price=price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand=brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color=color;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price=price;
}
}
public class PhoneTest {
public static void main(String[] args) {
Phone s=new Phone();
s.setBrand("apple");
s.setColor("white");
s.setPrice(5000);
System.out.println(s.getBrand()+"--"+s.getColor()+"--"+s.getPrice());
}
}