如何调用同一个包的另一个类中的方法?

发布于 2024-09-19 06:23:53 字数 78 浏览 4 评论 0原文

Java中如何调用同一个包的另一个类中的方法? 我所知道的是,使用一个对象,我们可以调用不同类中的方法。 还有其他方法可以调用不同类的方法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

庆幸我还是我 2024-09-26 06:23:53

创建 B: 类的实例,

B b=new B();
b.method();

或者在 B: 类中定义一个静态方法,

class B
{
 static void staticMethod();
}

并像这样调用它:

B.staticMethod();

Create an instance of Class B:

B b=new B();
b.method();

or define an static method in Class B:

class B
{
 static void staticMethod();
}

and call it like this:

B.staticMethod();
回眸一遍 2024-09-26 06:23:53

方法是对象方法类方法

对象方法:它应用于对象。您必须使用实例:

instance.method(args...);

类方法:它适用于类。它没有隐式实例。您必须使用类本身。它更像是过程式编程。

ClassWithStaticMethod.method(args...);

反射

通过反射,您可以通过 API 来以编程方式访问方法,无论是对象方法还是类方法。

实例方法:methodRef.invoke(instance, args...);
类方法:methodRef.invoke(null, args...);

Methods are object methods or 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.

Instance methods: methodRef.invoke(instance, args...);
Class methods: methodRef.invoke(null, args...);

一枫情书 2024-09-26 06:23:53

如果将该方法定义为静态方法,则无需先实例化该类即可使用它,但随后也没有可供使用的对象变量。

public class Foo {
   public static String Bar() {
      return "bla";
   }
}

在这种情况下,您可以使用 Foo.Bar() 来调用它。

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().

浅笑轻吟梦一曲 2024-09-26 06:23:53

来自 Fred Swartz(弗雷多龙)的笔记

有两种类型的方法。

  • 实例方法与对象关联并使用该对象的实例变量。这是默认设置。

  • 静态方法不使用定义它们的类的任何对象的实例变量。如果您将方法定义为静态,那么如果您尝试访问任何实例变量。您可以访问静态变量,但除了常量之外,这是不常见的。静态方法通常从参数中获取所有数据,并根据这些参数计算一些内容,而不引用变量。这是进行某种通用计算的典型方法。一个很好的例子是预定义的 Math 类中的许多实用方法。

限定静态调用

从定义类的外部,通过在实例方法前添加一个对象来调用实例方法,然后将该对象作为隐式参数传递给实例方法,例如,inputTF.setText("");

静态方法通过在类名前面加上前缀来调用,例如,Math.max(i,j);。奇怪的是,它也可以用一个对象来限定,这将被忽略,但将使用该对象的类。

示例

这是一个典型的静态方法:

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
    . . .
}

该方法使用或更改的唯一数据来自参数(当然或局部变量)。

为什么声明方法static

如果上面的mean() 方法没有声明为静态,那么只要从同一个类中调用它,它也能正常工作。如果从类外部调用并且未将其声明为静态,则必须使用对象对其进行限定(无用)。即使在类中使用时,也有充分的理由将方法定义为静态(如果可以的话)。

  • 文档。任何看到静态方法的人都会知道如何调用它(见下文)。同样,任何查看代码的程序员都会知道静态方法不能与实例变量交互,这使得阅读和调试更容易。
  • 效率。编译器通常会生成稍微更高效的代码,因为不需要将隐式对象参数传递给方法。

调用静态方法

有两种情况。

在同一个类内调用

只需写静态方法名称即可。例如:

// Called from inside the MyUtils class
double avgAtt = mean(attendance);

从类外部调用

如果从另一个类调用一个方法(静态或实例),则必须在方法名称之前给出一些内容,以指定定义该方法的类。对于实例方法,这是该方法将访问的对象。对于静态方法,应指定类名。例如:

// Called from outside the MyUtils class.
double avgAtt = MyUtils.mean(attendance); 

如果在它之前指定了一个对象,则该对象值将被忽略,并且将使用该对象的类。

访问静态变量

尽管static 方法无法访问实例变量,但它可以访问static 变量。静态变量的常见用途是定义“常量”。 Java 库中的示例有 Math.PIColor.RED。它们通过类名进行限定,因此您知道它们是静态。任何方法,无论是否是静态的,都可以访问静态变量。实例变量只能通过实例方法访问。

备用调用

有点奇怪但不推荐的是,可以使用类的对象而不是类名来访问静态方法。这很糟糕,因为它给人的印象是对象中的某些实例变量已被使用,但事实并非如此。

From the Notes of Fred Swartz (fredosaurus) :

There are two types of methods.

  • Instance methods are associated with an object and use the instance variables of that object. This is the default.

  • Static methods use 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.

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("");

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.

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

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.

  • 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.

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.

蓝咒 2024-09-26 06:23:53

如果它是静态方法,则可以使用类名代替对象来调用它。

If it's a static method, you can call it by using the class name in place of an object.

酷炫老祖宗 2024-09-26 06:23:53

您可以创建静态方法,也可以使用另一个类作为类的成员来调用构造函数中的函数。

public class aClass {
      private SomeOtherClass oc;
      public class aClass( SomeOtherClass otherClass) {
         oc = otherClass;
      }

      public callOtherClassMethod() {
         oc.otherClassMethod();
       }
    }

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();
       }
    }
云淡风轻 2024-09-26 06:23:53

按照以下格式进行操作:

classmehodisin.methodname();

例如:

MyClass1.clearscreen();

我希望这会有所帮助。
注意:该方法必须是静态的。

Do it in this format:

classmehodisin.methodname();

For example:

MyClass1.clearscreen();

I hope this helped.`
Note:The method must be static.

嗫嚅 2024-09-26 06:23:53

通过调用方法

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);
    }
}

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);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文