Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method function from another class?

Tags:

java

bluej

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){

    }
}

This is another 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

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

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

    }
}
like image 720
highspeedpog Avatar asked Oct 09 '14 02:10

highspeedpog


1 Answers

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, 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!");
    }
}
like image 79
MarsAtomic Avatar answered Oct 04 '22 13:10

MarsAtomic