为什么链表和那个遍历的方法要加static啊,不加就标红,问题是要实现一个数组的逆序输出,就不明白为啥要加static?


public class Demo04 {
    public static int[] reversePrint(ListNode head){
        LinkedList<Integer> stack = new LinkedList<Integer>();
        while (head!=null){
            stack.addLast(head.val);
            head = head.next;
        }
        int[] res = new int[stack.size()];
        for (int i = 0; i <res.length ; i++) {
            res[i] = stack.removeLast();
            System.out.println(res[i]);
        }

        return res;

    }
    private static class ListNode {
        int val;
        ListNode next;
        ListNode(int x){val = x;}
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        reversePrint(node1);
    }
}

因为静态方法不能调用非静态方法的属性和方法,使用时,只能将被调用的方法声明为静态的,而ListNode类之所以被声明为static的,主要是方便通过类名直接调用其属性值,不用额外new对象

加了static是静态方法,调用的时候不需要创建实例,可以直接通过类名调用

img


比如这样我创建一个demo对象,来调用这个方法,为什莫也不行啊

static只能访问static的方法和变量,否则new对象访问