Java规定构造方法和类名相同_不是说:java构造方法和类名一定要相同吗?为什么我看见很多构造方法跟类名不完全一致啊?隐藏了什么吗?...

比如以下代码。类名不是TestCar_EX才对吗?为什么构造方法名却是Car?我看见很多教程都是这么写的。晕。。。。。。。。。。。到底怎么样才是对的啊?

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

}

}

class Car

Car 也是一个java类啊。一个

java

文件中可以存在多个

class

但是只能有一个

public class

你这是两个类啊,

TestCar_EX

只有默认的无参数构造方法,只是为

Car

添加了构造方法。

你这是两个类,一个.java文件里只能有一个public修饰的类也就是你的TestCar_EX类,默认是无参的构造方法(不需要自己写),Car也是一个类,你写了他的有参数构造,当然他也有默认的无参构造。不知道这么说你懂没懂…

构造方法和类名必须一致,参见Java语言规范8.8. Constructor Declarations.

The SimpleTypeName in the ConstructorDeclarator must be the simple name of the class that contains the constructor declaration, or a compile-time error occurs.

这里的simple name就是不带包名的类名,区别于全限定名。

TestCar_EX 这个是main方法入口类,你new的是Car。你理解能力有问题,建议不要重试开发

一般的。。技术上的只适合某种特定的场合。没有那种技术可以在所有场合都适用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值