成员变量: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());
}
}