关于java:封装代码

35次阅读

共计 1880 个字符,预计需要花费 5 分钟才能阅读完成。

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);
    }
}

正文完
 0