简体   繁体   English

如何在 Java 中声明某种类型的变量?

[英]How do I declare a variable of certain type in Java?

I have this class called Imp.我有一个名为 Imp 的课程。

public class Imp{

}

so how can I have this variable, let's say its called iimmpp, with the type Imp, and it should be able to access globally.那么我怎样才能拥有这个变量,假设它称为 iimmpp,类型为 Imp,并且它应该能够全局访问。

public static Imp iimmpp;

where should I put this statement?我应该把这个声明放在哪里? Thanks.谢谢。

on your main class to create an object of imp,在你的主类上创建一个imp对象,

type:类型:

Imp iimmpp = new Imp();

In any class, since it's public and static you can operate with it from any other class with classname.iimmpp;在任何类中,由于它是公共和静态的,因此您可以从任何其他类中使用 classname.iimmpp 来操作它;

For instance, in a class named Foo例如,在一个名为 Foo 的类中

public class Foo {
    public static Imp iimmpp;
}

You can access it with Foo.iimmpp from any other class on your application您可以使用 Foo.iimmpp 从应用程序上的任何其他类访问它

Use this in your main method to create an variable of type Imp.在您的主方法中使用它来创建一个 Imp 类型的变量。 Imp iimmpp = new Imp(); Imp iimmpp = new Imp();

If you just want it to be accessible i the class then you can just write :如果你只是想让它在课堂上可以访问,那么你可以写:

public class Imp{
    public Imp iimmpp = new Imp();
}

when you instantiate this class you will still be able to retrieve the variable iimmpp because it has a public access.当您实例化此类时,您仍然可以检索变量iimmpp因为它具有public访问权限。

Put it in any other Static context where you will need to use it.将它放在您需要使用它的任何其他静态上下文中。

You can use it in any class that can see the Imp class (ie has imported the Imp class).您可以在任何可以看到Imp 类的类中使用它(即已导入Imp 类)。

Simply put it between the brackets of the class declaration.只需将它放在类声明的括号之间。 You can also put it inside of a static method, but then it will only be accessible within that method.您也可以将它放在静态方法中,但它只能在该方法中访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM