今天学习的内容是构造方法
package TestDemo02; public class Car { private String brand; private String color; private double price; public Car() { } public Car(String brand, String color, double price) { this.brand = brand; this.color = color; this.price = price; } public void printFeatures() { System.out.println("品牌: " + brand); System.out.println("颜色: " + color); System.out.println("价格: " + price + "元"); } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public void setColor(String color) { this.color = color; } public String getColor() { return color; } public void increasePrice() { price += 1000; } public void increasePrice(double amount) { price += amount; } public static void main(String[] args) { Car car1 = new Car(); car1.printFeatures(); Car car2 = new Car("BMW", "Black", 50000); car2.printFeatures(); System.out.println("获取品牌: " + car2.getBrand()); System.out.println("获取价格: " + car2.getPrice()); car2.setBrand("Audi"); car2.setColor("White"); System.out.println("设置后的品牌和颜色: " + car2.getBrand() + ", " + car2.getColor()); car2.increasePrice(); System.out.println("增加1000元后的价格: " + car2.getPrice()); car2.increasePrice(2000); System.out.println("增加2000元后的价格: " + car2.getPrice()); } }
package TestDemo02; public class Girl2 { String name; int age; boolean boyfriend; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isBoyfriend() { return boyfriend; } public void setBoyfriend(boolean boyfriend) { this.boyfriend = boyfriend; } public void showname(){ System.out.println("我的名字是:" + name); } public void showage(){ System.out.println("我的年龄是:" + age); } public void showboyfriend(){ System.out.println("是否有男朋友:" + boyfriend); } public static void main(String[] args) { Girl2 g2 = new Girl2(); g2.name = "貂蝉"; g2.age = 18; g2.boyfriend = false; g2.showname(); g2.showage(); g2.showboyfriend(); } }
package TestDemo02; public class Person { String name; int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { if(age>0&&age<150){ this.age = age; }else { this.age = 18; System.out.println("你输入的年龄有误!"); } } public void show(){ System.out.println("姓名:" + name + ",年龄:" + age); } public static void main(String[] args) { Person p = new Person(); p.show(); p.name = "zhangfei"; p.age = 18; p.show(); } }
再接再厉!!