【JavaOOP】1、类和对象、构造方法和this关键字

1. 类和对象

类和对象的关系:
1、类是抽象的,是现实世界中很多个同类事物的抽象。
2、对象是具体的,是看得见也摸得着的现实世界实实在在的个体。
3、使用对象时首先进行实例化,再为其属性赋值,最后调用方法。

以一个汽车类和其对象的构造为例进行说明:

image-20240710134611063

具体实现代码如下:

/**
 * 汽车类
 */
public class Car {

    public String brand;            // 品牌
    public String color;            // 颜色
    public int wheels;              // 轮子数
    public double price;            // 价格

    public void start() {
        System.out.println("汽车正在启动。。。");
    }

    public void run() {
        System.out.println("一辆价格为" + price + "的" + color + "的" + wheels + "轮" + brand + "汽车正在奔驰!");
    }

    public void stop() {
        System.out.println("汽车停止。。。");
    }
}
@Test
public void test01(){
    // 1、构造一辆汽车
    Car car = new Car();
    // 2、汽车类设置属性
    car.brand = "大众";
    car.color = "黑色";
    car.wheels = 4;
    car.price = 100000;
    // 3、调用方法
    car.start();
    car.run();
    car.stop();
}

2. 构造方法和this关键字

2.1 构造方法

1、构造方法一般定义为public的。[备注:在单例模式时会用到private]
2、构造方法命名与类名相同,没有返回值,包括void类型。
3、构造方法名与类名必须一致
4、一个类如果没有提供构造方法,则JVM会为我们提供一个默认无参的构造方法。但是,一旦我们定义了自己的构造方法,则系统不会再为我们提供任何形式的构造方法了。
5、构造方法的作用:就是实现局部变量为全局赋值(简化了对对象的赋值操作)。

具体实现代码如下:

public String brand;            // 品牌
public String color;            // 颜色
public int wheels;              // 轮子数
public double price;            // 价格

/**
 * 构造方法:
 * 1、作用:简化属性的赋值
 * 2、默认情况下,系统会为我们提供一个无参的构造方法,如果定义了自己的构造方法,系统就不会再为我们提供任何形式的构造方法了。
 * <p>
 * this关键字的用法:
 * 1、代表当前正在使用的那个对象
 * 2、this代表访问全局变量(成员变量)的值,特别是当局部变量与全局变量命名冲突时。
 * 3、this(【参数列表】)可以调用本类的其他构造方法。这句必须要写在方法内第一行。
 */
public Car() {
    System.out.println("无参构造方法");
}

public Car(String brand, String color, int wheels, double price) {
    this(brand, color, price);
    this.brand = brand;
    this.color = color;
    this.wheels = wheels;
    this.price = price;
    System.out.println("四参构造方法");
}

public Car(String brand, String color, double price) {
    this(brand, color);
    this.brand = brand;
    this.color = color;
    this.price = price;
    System.out.println("三参构造方法");
}

public Car(String brand, String color) {
    this();
    this.brand = brand;
    this.color = color;
    System.out.println("二参构造方法");
}

2.2 this关键字

1、如果在构造方法中使用this,代表通过局部变量为全局变量进行赋值。如果没有this,根据软件开发中的就近原则,就会自己赋值给自己。
2、this在构造方法中就代表当前构造出来的那个对象。
3、this([参数列表])代表调用本类的其他构造方法,它只能放在调用的构造方法的第一行上,所以,在一个构造方法中只能调用一次this([参数列表])

2.3 使用构造方法简化赋值操作

@Test
public void test02(){
    // 1、构造一个汽车对象
    Car car = new Car("奔驰", "黑色", 4, 600000);
    // 2、调用方法
    car.start();
    car.run();
    car.stop();
    // 3、打印汽车对象
    System.out.println(car);
}
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

浮生146

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

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

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

打赏作者

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

抵扣说明:

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

余额充值