简体   繁体   中英

Java method().method() calling

How, if it's possible, can you call a method from another method's return ?

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 .

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.

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.

In your case you need to do an explicit cast to the Point and then call the intended method. Otherwise you need to have the arraylist defined in java generics way as mentioned by @Makoto.

Casting way is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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