Java:在另一个类中使用该类中的对象 [英] Java: using object from class in another class

查看:252
本文介绍了Java:在另一个类中使用该类中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的文件。在下面的文件中,我创建一个具有属性的新对象,并创建一种检索该属性的方法。

I have two different files. In the file below I create a new object with an attribute and I create a method to retrieve that attribute.

public class Journey
{
    public double singleCost;

    public void setSingleCost(double cost) {
        singleCost = cost;
    }

    public double getSingleCost() {
        return singleCost;
    }

    public static void main (String[] args) {
        Journey leicester_loughborough = new Journey();
        leicester_loughborough.setSingleCost(2.5);

        Journey leicester_nottingham = new Journey();
        leicester_nottingham.setSingleCost(3.5);
    }
}

在一个单独的文件中,我想打印该对象的属性。不过,我不确定该怎么做。以下似乎无效。

In a separate file, I would like to print out that object's attribute. I'm not sure how to do that though. The following doesn't seem to work.

public class JourneyMethods
{    
    public static void main (String[] args) {
        System.out.println(leicester_loughborough.getSingleCost());
    }
}

感谢您的帮助。

推荐答案

您对这种主要方法的想法太多了。

You are thinking about this too much as main methods.

您的 JourneyMethods 主要方法对 Journey 一无所知除非您告诉。如果创建对 Journey的引用, JourneyMethods 将能够与 Journey 实例进行交互

Your JourneyMethods main method knows nothing about the Journey class unless you tell it. JourneyMethods will be able to interact with a Journey instance if you create a reference to a Journey.

这篇关于Java:在另一个类中使用该类中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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