java构造函数示例(构造方法)

时间:2022-05-08 19:06:03 

TestCar.java


public class TestCar {
    public static void main(String[] args) {
        Car c1 = new Car();
        c1.color = "red";
        c1.brand = "xxx";//如果这辆汽车有很多属性,这样一一赋值不是很麻烦?有没有办法一生产出来就设定它的属性(初始化)吗?有~~~看下面      
    }  
}

class Car {
    String color;
    String brand;

    void run() {
        System.out.printf("I am running...running..running~~~~\n");
    }  

    void showMessage() {
        System.out.printf("汽车颜色:%s, 汽车品牌:%s\n", color, brand);
    }  
}

改进后的TestCar_EX.java


/*什么是构造方法*/
public class TestCar_EX {
    public static void main(String[] args) {
        Car c1 = new Car("red", "xxx");
    }  
}

class Car {
    String color;
    String brand;

    public Car(String color, String brand) {
        this.color = color;             //这里的this是这个对象的意思.第一个color是这个对象的color属性,第二个是局部变量color
        this.brand = brand;             //同上
    }  

    void run() {
        System.out.printf("I am running...running..running~~~~\n");
    }  

    void showMessage() {
        System.out.printf("汽车颜色:%s, 汽车品牌:%s\n", color, brand);
    }  
}

标签:java,构造方法
0
投稿

猜你喜欢

  • springboot+rabbitmq实现智能家居实例详解

    2022-09-05 12:23:39
  • 简单实现Java web服务器

    2023-10-11 16:47:13
  • android调试工具DDMS的使用详解

    2023-06-21 09:06:22
  • Java web spring异步方法实现步骤解析

    2023-12-19 03:14:58
  • Spring 应用中集成 Apache Shiro的方法

    2023-02-18 05:44:55
  • Java ArrayList中存放引用数据类型的方式

    2023-11-16 15:23:46
  • 让Java后台MySQL数据库能够支持emoji表情的方法

    2022-12-30 04:24:45
  • java中类与对象的使用详情

    2023-09-27 17:10:43
  • 使用springCloud+nacos集成seata1.3.0搭建过程

    2022-06-19 02:48:47
  • 宝塔面板配置及部署javaweb教程(全网最全)

    2023-11-10 15:26:27
  • 两种JAVA实现短网址服务算法

    2023-05-08 12:17:30
  • 深入理解Java序列化与反序列化

    2023-01-24 00:27:53
  • Mybatis整合达梦数据库的完整步骤记录

    2023-11-23 07:15:37
  • 详解springboot之jackson的两种配置方式

    2021-11-03 11:01:21
  • 详谈C++引用&和指针在作为形参时的区别

    2023-12-13 16:50:49
  • android 6.0 写入SD卡的权限申请实例讲解

    2023-07-27 03:12:37
  • spring boot入门之诞生背景及优势影响

    2021-09-16 06:31:57
  • Java SpringBoot实现AOP

    2023-05-31 05:49:30
  • spring scheduled单线程和多线程使用过程中的大坑

    2022-09-24 05:51:10
  • springboot结合maven配置不同环境的profile方式

    2022-05-28 12:00:16
  • asp之家 软件编程 m.aspxhome.com