从Java中的另一个类运行方法

时间:2017-03-11 01:59:49

标签: java methods

我要做的是从另一个类new Link().populateList();运行一个方法。我尝试过扩展我的Link类,并使用不同的参数填充Link()populateList()无济于事。任何人都可以把我推向正确的方向吗?以下是我的代码:

具有main()方法

的Reverse.java类
package main;

public class Reverse {

    public static void main(String[] args){
        new Link().populateList();
    }
}

Link.java

package main;

public class Link {
    public Link next;

    public String name;
    public int age;

    public Link(String name, int age){
        this.name = name;
        this.age = age;
    }

    public void displayInformation(){
        System.out.println("Name: "+ name + ", Age: " + age);
    }

    public void populateList(){
        LinkedList people = new LinkedList();

        people.insertLinks("John", 21);
        people.insertLinks("David", 27);
        people.insertLinks("Abraham", 19);
    }
}

LinkedList.java

package main;

public class LinkedList {

    public Link first;

    public boolean isEmpty(){
        return(first == null);
    }
    public void insertLinks(String name, int age){
        Link link = new Link(name, age);

        link.next = first;
        first = link;
    } 
    public void display(){
        Link link = first;

        while(link != null){
            link.displayInformation();
        }
    }
}

1 个答案:

答案 0 :(得分:3)

public void populateList(){
    LinkedList people = new LinkedList();

    people.insertLinks("John", 21);
    people.insertLinks("David", 27);
    people.insertLinks("Abraham", 19);
}

方法正在运行,但它没有做任何可见的事情。它创建一个链表,添加三个条目,然后抛出列表。它不会调用people.display(),也不会调用return people;,不会调用任何内容。