简体   繁体   English

Java method()。method()调用

[英]Java method().method() calling

How, if it's possible, can you call a method from another method's return ? 如果可能的话,如何从另一个方法的return调用一个method

For example... 例如...

class Example {
    public static void main(String[] args) {
        Point t1 = new Point(0,0);
        Point t2 = new Point(0,1);
        ArrayList pointContainer = new ArrayList();
        pointContainer.add(0,t1);
        pointContainer.add(0,t2);    // We now have an ArrayList containing t1 & t2
        System.out.println(pointContainer.get(1).getLocation()); // The problem area
    }
}

In the poorly written example, I'm trying to invoke the getLocation() method (part of java.swing.awt ) on index item 1 of pointContainer . 在写得不好的例子,我想调用getLocation()方法(部分java.swing.awt对指数第1项) pointContainer

When trying to compile the program, I get the following error... 尝试编译程序时,出现以下错误...

HW.java:20: error: cannot find symbol
        System.out.println(test.get(1).getLocation());
                                  ^
  symbol:   method getLocation()
  location: class Object

Could someone please help me with this problem. 有人可以帮我解决这个问题。

First, type your ArrayList so that Java can know what objects are coming out of it. 首先,键入您的ArrayList,以便Java可以知道从中产生了什么对象。

List<Point> pointContainer = new ArrayList<Point>();

Then, any objects you retrieve from that ArrayList will be of type Point , so you can perform operations on them. 然后,从该ArrayList检索到的所有对象都将是Point类型,因此您可以对其执行操作。

In your case you need to do an explicit cast to the Point and then call the intended method. 在您的情况下,您需要对Point进行显式转换,然后调用所需的方法。 Otherwise you need to have the arraylist defined in java generics way as mentioned by @Makoto. 否则,您需要按@Makoto所述以java泛型方式定义arraylist。

Casting way is 投射方式是

((Point)pointContainer.get(1)).getLocation()

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

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