简体   繁体   English

如何从另一个 class 调用方法 function?

[英]How to call a method function from another class?

I'm writing a java project that has three different classes.我正在编写一个包含三个不同类的 java 项目。 This is what i have have so far.这是我到目前为止所拥有的。 I'm just stuck on how do you call a method function from another class to another class. I have written 2 classes already.我只是停留在如何从另一个 class 调用方法 function 到另一个 class。我已经写了 2 个类。 I got the "Date" class and "TemperatureRange" class done;我完成了“日期”class 和“温度范围”class; now i'm trying to call those 2 classes into "WeatherRecord" class. I'm not sure if i'm explaining this right.现在我正在尝试将这两个类调用到“WeatherRecord”class 中。我不确定我的解释是否正确。

public class WeatherRecord //implements Record
{

    private String TemperatureRangetoday;
    private String TemperatureRangenormal;
    private String TemperatureRangerecord;


    public static void main (String[] args){

    }
}

This is another class这是另一个 class

public class Date
{
    public static String date(String date, String month, String year){
        String rdate = date + " " +month + " " +year;
        return rdate;   
    }
}

And here's another class这是另一个 class

public class TemperatureRange
{
    public static String TempRange (String high, String low){

        String rTempRange = high +"high" + " "+low+"low";
        return rTempRange;

    }
}

You need a reference to the class that contains the method you want to call.您需要对包含要调用的方法的类的引用。 Let's say we have two classes, A and B. B has a method you want to call from A. Class A would look like this:假设我们有两个类,A 和 B。B 有一个你想从 A 调用的方法。类 A 看起来像这样:

public class A
{
    B b; // A reference to B

    b = new B(); // Creating object of class B

    b.doSomething();  // Calling a method contained in class B from class A
}

B, which contains the doSomething() method would look like this: B,其中包含 doSomething() 方法将如下所示:

public class B
{
    public void doSomething()
    {
        System.out.println("Look, I'm doing something in class B!");
    }
}

In class WeatherRecord :在类WeatherRecord

First import the class if they are in different package else this statement is not requires如果它们在不同的包中,则首先导入类,否则不需要此语句

Import <path>.ClassName



Then, just referene or call your object like:然后,只需引用或调用您的对象,如:

Date d;
TempratureRange tr;
d = new Date();
tr = new TempratureRange;
//this can be done in Single Line also like :
// Date d = new Date();



But in your code you are not required to create an object to call function of Date and TempratureRange.但是在您的代码中,您不需要创建一个对象来调用 Date 和 TempratureRange 的函数。 As both of the Classes contain Static Function , you cannot call the thoes function by creating object.由于两个类都包含静态函数,因此您不能通过创建对象来调用 thoes 函数。

Date.date(date,month,year);   // this is enough to call those static function 


Have clear concept on Object and Static functions.对对象和静态函数有清晰的概念。 Click me点击我

For calling the method of one class within the second class, you have to first create the object of that class which method you want to call than with the object reference you can call the method.要在第二个类中调用一个类的方法,您必须首先创建该类的对象,您要调用哪个方法,而不是使用可以调用该方法的对象引用。

class A {
   public void fun(){
     //do something
   }
}

class B {
   public static void main(String args[]){
     A obj = new A();
     obj.fun();
   }
}

But in your case you have the static method in Date and TemperatureRange class.但是在您的情况下,您在 Date 和 TemperatureRange 类中有静态方法。 You can call your static method by using the class name directly like below code or by creating the object of that class like above code but static method ,mostly we use for creating the utility classes, so best way to call the method by using class name.您可以像下面的代码一样直接使用类名来调用静态方法,也可以像上面的代码一样创建该类的对象,但静态方法主要用于创建实用程序类,因此最好使用类名来调用该方法. Like in your case -就像你的情况 -

public static void main (String[] args){
  String dateVal = Date.date("01","11,"12"); // calling the date function by passing some parameter.

  String tempRangeVal = TemperatureRange.TempRange("80","20"); 
}

You need to instantiate the other classes inside the main class;您需要在主类中实例化其他类;

Date d = new Date(params);
TemperatureRange t = new TemperatureRange(params);

You can then call their methods with:然后你可以调用他们的方法:

object.methodname(params);
d.method();

You currently have constructors in your other classes.您目前在其他类中有构造函数。 You should not return anything in these.你不应该返回这些中的任何东西。

public Date(params){
    set variables for date object
}

Next you need a method to reference.接下来你需要一个方法来引用。

public returnType methodName(params){
  return something;
}

You need to understand the difference between classes and objects.您需要了解类和对象之间的区别。 From theJava tutorial :Java 教程

An object is a software bundle of related state and behavior对象是相关状态和行为的软件包

A class is a blueprint or prototype from which objects are created类是创建对象的蓝图或原型

You've defined the prototypes but done nothing with them.您已经定义了原型,但没有对它们做任何事情。 To use an object, you need to create it.要使用对象,您需要创建它。 In Java, we use the new keyword.在 Java 中,我们使用new关键字。

new Date();

You will need to assign the object to a variable of the same type as the class the object was created from.您需要将对象分配给与创建对象的类具有相同类型的变量。

Date d = new Date();

Once you have a reference to the object you can interact with it一旦你有了对象的引用,你就可以与它进行交互

d.date("01", "12", "14");

The exception to this is static methods that belong to the class and are referenced through it例外是属于该类并通过它引用的静态方法

public class MyDate{
  public static date(){ ... }
}

...
MyDate.date();

In case you aren't aware, Java already has a class for representing dates, you probably don't want to create your own.如果您不知道,Java 已经有一个用于表示日期的类,您可能不想创建自己的类。

import <path>;
 My main java program:

import method;
import java.util.Scanner;
public class Main {
    public static void main(String[] args){
        Scanner n = new Scanner(System.in);
        int a,b,c;
        double area,s;
        System.out.print("Enter the 1st side->");
        a = n.nextInt();
        System.out.print("Enter the 2nd side->");
        b = n.nextInt();
        System.out.print("Enter the 3rd side->");
        c = n.nextInt();
        s=(a+b+c)/2.0;
        area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
        System.out.println("Area is = "+area);
        //factorial function is contained in the class method
        System.out.print(method.factorial(a));
    }
}

There's a hack .有一个黑客

When you're creating the activity classes of your app, chose one (most logically your start-up activity class) as the " master ", and have all other activity classes extend the master.当您创建应用程序的活动类时,选择一个(最合乎逻辑的是您的启动活动类)作为“主人”,并让所有其他活动类扩展主人。 Any public method you create in the master should be callable from any of the other activity classes, provided the variables and parameters that method uses are also known to the other activity classes.您在 master 中创建的任何公共方法都应该可以从任何其他活动类调用,前提是该方法使用的变量和参数也为其他活动类所知。

This is for public method and in same package both classes

1) create object that class and call method
e.g. A obj = new A();
       obj.m();

2) using inheritance e.g. extends 

public class A extends B
 {
 obj.m();
 }

3) if static method then directly call via class name
   A.m();

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

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