一,汽车类
public class CarText {
public static void main(String[] args) {
Car car = new Car();
car.setBrand("BMW");
car.setColor("黑");
car.setPrice(9.9);
car.setLength(0.1);
System.out.println(car.getBrand());
System.out.println(car.getColor());
System.out.println(car.getPrice());
System.out.println(car.getLength());
//BMW
//黑
//9.9
//0.1
}
}
class Car{
private String color;//颜色
private String brand;//品牌
private double price;//价格
private double length;//长度
public void start(){
System.out.println("我的小车启动了");
}
public void stop(){
System.out.println("我的雄安车熄火了");
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
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 double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
}
二,方法重载
public class OverrideDemo {
String name;
int age;
public void main(String[] args) {
moth();
moth("孙悟空",800);
moth(800,"孙悟空");
}
public void moth(String name,int age) {
this.name=name;
this.age=age;
}
public void moth(int age,String name) {
this.age=age;
this.name=name;
}
public void moth(){
}
}//调用方法的参数必须要一一对应,才能调用相应的方法
三,构造方法
public class TestConstructor {//默认会创建无参构造器,如果自定义有参构造器,无参构造器就会被覆盖,这是需要手动添加无参构造器。
public static void main(String[] args) {
Dog dog1 = new Dog();
Dog dog2 = new Dog("旺财");
//为了创建对象时方便,需要手动为本类提供一个无参构造
}
}
class Dog{
String name;//姓名
int age;//年龄
String host;//主人
public Dog(){
System.out.println("无参构造");
}
public Dog(String name){
System.out.println("含参构造,小狗的名字为:"+name);
}
}