比如以下代码。类名不是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。你理解能力有问题,建议不要重试开发
一般的。。技术上的只适合某种特定的场合。没有那种技术可以在所有场合都适用