您似乎对 Java 或面向对象编程很陌生。
在Java中创建对象有两个步骤:声明和初始化
声明表示您正在声明某事存在。
例如:String title; 表示,存在一个名为 title 的字符串对象。
Initialization 正在为其赋值。即:title = "Hello World!";。但是在初始化一个对象之前,您需要确保它已被声明。你也可以在一个语句中结合声明和初始化:String title = "Hello World!";
对象的范围取决于您声明该对象的位置。
如果你在这样的类中声明它:
class Car {
String name; //These are called fields
static String author = "Farseen"
public void doSomething() {..../*can access name and author*/}
public static void doSomething() {..../*can access author only*/}
}
类中的所有东西都可以访问它,除了静态(我们稍后会讲到)方法。这些被称为字段
如果你在一个方法中声明它,只有那个方法可以访问它:
class Car {
public void doSomething() {
String name = "BMW"; //These are called local variables
}
public void doSomeOtherThing() {
//Cannot acccess name
}
}
这些被称为局部变量
如果你在一个类之外声明它,抱歉 Java 不允许你这样做。一切都必须在一个类中。
您可以在方法之外为声明添加前缀,即带有访问修饰符的字段:
public :使任何人都可以访问该字段。合法:
Car myCar = new Car();System.out.println(myCar.name);
private :使该字段只能被类内的方法(函数)访问。 非法到 :
Car myCar = new Car();System.out.println(myCar.name);
protected :使该类的子类可以访问该字段。用户也无法访问它,例如私有。
现在加入 static 修饰符:
它表示字段或方法(函数)属于汽车的整个物种,而不是单个汽车。
像这样访问静态字段author 是合法的:Car.author 无需创建单独的汽车,虽然它是合法的:new Car().author
静态的东西只知道静态的东西,不知道个别的东西。
Java 中没有全局变量的概念。虽然,您可以使用以下方式实现它:
class Globals {
public static String GLOBAL_VARIABLE_MESSAGE = "Hello World!";
}
并在代码中的某处使用Globals.GLOBAL_VARIABLE_MESSAGE
希望对你有帮助!
编辑:参考添加到问题中的代码
class A{ //Parenthesis are NOT needed
// or allowed in class definition:
// 'class A()' is wrong
String b;
public void c(){
//some code in here
}
}
class C{ //Same here. No parenthesis needed
A a = new A(); //Q: Is this ok and if it is ok what is this mean??
//A: Yes, completely ok.
// This means you added
// a field 'a' of type A to the class C
public void p(){
a.c(); //Q: Is this possible??
//A: Of course
}
}