Java 如何调用同一个包的另一个类中的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3713643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a method in another class of the same package?
提问by
How to call a method, which is in another class of same package in Java? What I know is, using an object we can call a method from a different class. Is there any other way to call a method of different class?
如何调用Java中同一包的另一个类中的方法?我所知道的是,使用一个对象,我们可以调用来自不同类的方法。有没有其他方法可以调用不同类的方法?
回答by AaronM
If it's a static method, you can call it by using the class name in place of an object.
如果它是静态方法,则可以使用类名代替对象来调用它。
回答by halfdan
If you define the method as static you can use it without instantiating the class first, but then you also dont have the object variables available for use.
如果您将方法定义为静态方法,则无需先实例化类即可使用它,但是您也没有可用的对象变量。
public class Foo {
public static String Bar() {
return "bla";
}
}
In that case you could call it with Foo.Bar()
.
在这种情况下,您可以使用Foo.Bar()
.
回答by helios
Methods are object methodsor class methods.
方法是对象方法或类方法。
Object methods:it applies over an object. You have to use an instance:
对象方法:它适用于一个对象。你必须使用一个实例:
instance.method(args...);
Class methods:it applies over a class. It doesn't have an implicit instance. You have to use the class itself. It's more like procedural programming.
类方法:它适用于一个类。它没有隐式实例。您必须使用类本身。它更像是过程式编程。
ClassWithStaticMethod.method(args...);
Reflection
反射
With reflection you have an API to programmatically access methods, be they object or class methods.
通过反射,您可以通过 API 以编程方式访问方法,无论是对象方法还是类方法。
Instance methods: methodRef.invoke(instance, args...);
Class methods: methodRef.invoke(null, args...);
实例方法:methodRef.invoke(instance, args...);
类方法:methodRef.invoke(null, args...);
回答by It Grunt
You can either create a static method or use the other class as a member of your class calling the function in the constructor.
您可以创建一个静态方法,也可以将另一个类用作在构造函数中调用该函数的类的成员。
public class aClass {
private SomeOtherClass oc;
public class aClass( SomeOtherClass otherClass) {
oc = otherClass;
}
public callOtherClassMethod() {
oc.otherClassMethod();
}
}
回答by Gustavo Puma
Create an instance of Class B:
创建 B 类的实例:
B b=new B();
b.method();
or define an static method in Class B:
或者在 B 类中定义一个静态方法:
class B
{
static void staticMethod();
}
and call it like this:
并这样称呼它:
B.staticMethod();
回答by Epic
Do it in this format:
以这种格式执行:
classmehodisin.methodname();
classmehodisin.methodname();
For example:
例如:
MyClass1.clearscreen();
MyClass1.clearscreen();
I hope this helped.` Note:The method must be static.
我希望这会有所帮助。` 注意:该方法必须是静态的。
回答by Jaken Herman
From the Notes of Fred Swartz (fredosaurus):
来自 Fred Swartz (fredosaurus) 的笔记:
There are two types of methods.
有两种类型的方法。
Instance methodsare associated with an object and use the instance variables of that object. This is the default.
Static methodsuse no instance variables of any object of the class they are defined in. If you define a method to be static, you will be given a rude message by the compiler if you try to access any instance variables. You can access static variables, but except for constants, this is unusual. Static methods typically take all they data from parameters and compute something from those parameters, with no reference to variables. This is typical of methods which do some kind of generic calculation. A good example of this are the many utility methods in the predefined
Math
class.
实例方法与一个对象相关联并使用该对象的实例变量。这是默认设置。
静态方法不使用定义它们的类的任何对象的实例变量。如果将方法定义为静态方法,则在尝试访问任何实例变量时编译器会给出粗鲁的消息。您可以访问静态变量,但除了常量,这是不寻常的。静态方法通常从参数中获取所有数据,并从这些参数中计算出一些东西,而不引用变量。这是进行某种通用计算的典型方法。一个很好的例子是预定义
Math
类中的许多实用方法。
Qualifying a static call
限定静态调用
From outside the defining class, an instance method is called by prefixing it with an object, which is then passed as an implicit parameter to the instance method, eg, inputTF.setText("");
从定义类的外部,通过在它前面加上一个对象来调用实例方法,然后将其作为隐式参数传递给实例方法,例如, inputTF.setText("");
A static method is called by prefixing it with a class name, eg, Math.max(i,j);
. Curiously, it can also be qualified with an object, which will be ignored, but the class of the object will be used.
静态方法是通过在它前面加上一个类名来调用的,例如,Math.max(i,j);
。奇怪的是,它也可以用一个对象来限定,该对象将被忽略,但会使用该对象的类。
Example
例子
Here is a typical static method:
这是一个典型的静态方法:
class MyUtils {
. . .
//================================================= mean
public static double mean(int[] p) {
int sum = 0; // sum of all the elements
for (int i=0; i<p.length; i++) {
sum += p[i];
}
return ((double)sum) / p.length;
}//endmethod mean
. . .
}
The only data this method uses or changes is from parameters (or local variables of course).
此方法使用或更改的唯一数据来自参数(或当然是局部变量)。
Why declare a method static
为什么要声明一个方法 static
The above mean()
method would work just as well if it wasn't declared static, as long as it was called from within the same class. If called from outside the class and it wasn't declared static, it would have to be qualified (uselessly) with an object. Even when used within the class, there are good reasons to define a method as static when it could be.
如果上面的mean()
方法没有被声明为静态的,只要它是从同一个类中调用的,它也能正常工作。如果从类外部调用并且它没有被声明为静态的,它就必须(无用地)用一个对象进行限定。即使在类中使用,也有充分的理由将方法定义为静态方法。
- Documentation.Anyone seeing that a method is static will know how to call it (see below). Similarly, any programmer looking at the code will know that a static method can't interact with instance variables, which makes reading and debugging easier.
- Efficiency.A compiler will usually produce slightly more efficient code because no implicit object parameter has to be passed to the method.
- 文档。任何看到方法是静态的人都会知道如何调用它(见下文)。同样,任何查看代码的程序员都会知道静态方法不能与实例变量交互,这使得阅读和调试更容易。
- 效率。编译器通常会生成更高效的代码,因为无需将隐式对象参数传递给方法。
Calling static methods
调用静态方法
There are two cases.
有两种情况。
Called from within the same class
从同一个类中调用
Just write the static method name. Eg:
只需写下静态方法名称。例如:
// Called from inside the MyUtils class
double avgAtt = mean(attendance);
Called from outside the class
从课外调用
If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined. For instance methods, this is the object that the method will access. For static methods, the class name should be specified. Eg:
如果从另一个类调用方法(静态或实例),则必须在方法名称之前给出某些内容以指定定义该方法的类。对于实例方法,这是该方法将访问的对象。对于静态方法,应指定类名。例如:
// Called from outside the MyUtils class.
double avgAtt = MyUtils.mean(attendance);
If an object is specified before it, the object value will be ignored and the the class of the object will be used.
如果在它之前指定了一个对象,则该对象值将被忽略并使用该对象的类。
Accessing static variables
访问静态变量
Altho a static
method can't access instance variables, it can access static
variables. A common use of static variables is to define "constants". Examples from the Java library are Math.PI
or Color.RED
. They are qualified with the class name, so you know they are static
. Any method, static
or not, can access static
variables. Instance variables can be accessed only by instance methods.
尽管static
方法不能访问实例变量,但它可以访问static
变量。静态变量的一个常见用途是定义“常量”。Java 库中的示例是Math.PI
或Color.RED
。它们用类名限定,所以你知道它们是static
. 任何方法,static
与否,都可以访问static
变量。实例变量只能通过实例方法访问。
Alternate Call
备用电话
What's a little peculiar, and not recommended, is that an object of a class may be used instead of the class name to access static methods. This is bad because it creates the impression that some instance variables in the object are used, but this isn't the case.
有点奇怪且不推荐的是,可以使用类的对象代替类名来访问静态方法。这很糟糕,因为它给人的印象是使用了对象中的某些实例变量,但事实并非如此。
回答by Pavan Kumar
By calling method
通过调用方法
public class a
{
void sum(int i,int k)
{
System.out.println("THe sum of the number="+(i+k));
}
}
class b
{
public static void main(String[] args)
{
a vc=new a();
vc.sum(10 , 20);
}
}