我有一个与OOP有关的问题.
如果我们在方法之外创建一个对象,那么效果是什么.
这个对象变得全球化吗?
这是一些代码..
class A(){
String b;
public void c(){
//some code in here}
}
class C(){
A a = new A(); //is this ok and if it is ok what is this mean??
public void p(){
a.c(); //Is this possible??
}
}
Run Code Online (Sandbox Code Playgroud)
您似乎对Java或面向对象编程非常陌生.
在Java中创建对象有两个步骤:声明和初始化
声明意味着你宣称存在某些东西.例如:String title;表示存在名为title的字符串对象.
初始化是为它赋值.即: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*/}
}
Run Code Online (Sandbox Code Playgroud)
类中的所有内容都可以访问它,除了静态(我们将在一段时间内完成)方法.这些方法称为字段
如果你在方法中对它进行decalare,那么只有该方法才能访问它:
class Car {
public void doSomething() {
String name = "BMW"; //These are called local variables
}
public void doSomeOtherThing() {
//Cannot acccess name
}
}
Run Code Online (Sandbox Code Playgroud)
这些被称为局部变量
如果你在一个类之外声明它,抱歉Java不允许你这样做.一切都必须在课堂上.
您可以在方法之外添加前缀声明,即具有访问修饰符的字段:
公共:使任何人都可以访问该字段.合法的是:
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!";
}
Run Code Online (Sandbox Code Playgroud)
并使用它在代码中的某处使用它 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
}
}
Run Code Online (Sandbox Code Playgroud)