封装代码

Car类

package com.cy;
//通过类来描述一类事物,把事物的属性当做成员变量,把行为当做方法
public class Car {
 private String color;
  private double price;
   private String brand;
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
}

测试类

package com.cy;
public class Test01 {
    public static void main(String[] args) {
        Car c = new Car();
//        c.print(); //全都是默认值
//        c.brand="奔驰";
//        c.color="粉色";
//        c.price=9999999.0;
//        c.print();
//        c.run();
//        c.consume();
 }
}

Teacher类

package com.cy;
//创建老师类:
// 分析:
// 属性:性别,名字,授课内容
// 功能:讲课
public class Teacher {
    String name;
    String sex;
    String subject;
    public void lecture(){
        System.out.println("正在讲课");
    }
    public void print(){
        System.out.println(name+sex+subject);
    }
}

测试类

package com.cy;
/**
 * @Author 张鹏宇
 * @Date 2021/3/25 10:20
 */public class Test02 {
    public static void main(String[] args) {
        Teacher t = new Teacher();
        t.name="张三";
        t.sex="男";
        t.subject="java";
        t.print();
    }
}

Student类

package com.cy;
/**
 * @Author 张鹏宇
 * @Date 2021/3/25 10:54
 */public class Student {
    private String name;
    private int age;
    private String subject;
//  get(获取值)   set(设置值)
 public String getName(){
        return name;
    }
    public void setName(String name){
        this.name =name;
//      null 张三 this指代当前对象
 }
//
 public void setAge(int age){
        this.age=age;
    }
    public int getAge(){
        return age;
    }
    public void setSubject(String subject){
        this.subject=subject;
    }
    public String getSubject(){
        return subject;
    }
    public void eat(){
        System.out.println("正在吃饭");
    }
    public void sleep(){
        System.out.println("正在睡觉");
    }
    public void play(){
        System.out.println("正在玩耍");
    }
}

测试类

package com.cy;
/**
 * @Author 张鹏宇
 * @Date 2021/3/25 10:56
 */public class Test03 {
    public static void main(String[] args) {
        Student s = new Student();
//        s.name="张三"; 被private修饰的成员变量不能再直接访问
 s.setName("张三");
        s.setAge(18);
        s.setSubject("java");
//        String name = s.getName();
 System.out.println(s.getName());
        System.out.println(s.getAge());
        System.out.println(s.getSubject());
        System.out.println(s);
    }
}

你可能感兴趣的:(java)