如何从另一个类调用方法函数? [英] How to call a method function from another class?

查看:188
本文介绍了如何从另一个类调用方法函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个包含三个不同类的java项目。这是我到目前为止所拥有的。我只是坚持你如何从另一个类调用方法函数到另一个类。我已经写了两门课。我完成了Date类和TemperatureRange类;现在我试图将这两个类称为WeatherRecord类。我不确定我是否正确解释这一点。

I'm writing a java project that has three different classes. 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. I got the "Date" class and "TemperatureRange" class done; now i'm trying to call those 2 classes into "WeatherRecord" class. I'm not sure if i'm explaining this right.

public class WeatherRecord //implements Record
{

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


    public static void main (String[] args){

    }
}

这是另一个类

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

这是另一个类

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

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

    }
}


推荐答案

您需要对包含要调用的方法的类的引用。假设我们有两个类,A和B. B有一个你想从A调用的方法.A类看起来像这样:

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:

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,其中包含doSomething()方法如下所示:

B, which contains the doSomething() method would look like this:

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

这篇关于如何从另一个类调用方法函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆