java技术练习(第五天):面对对象练习

一,汽车类

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员慕慕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值