猿问

使用 args 时,不能从静态引用非静态

这是代码。错误发生在第 2 行。


public class TestStack1 {


    public static void main(String[] args) {

        FixCapacityStackOfString fcstack = new FixCapacityStackOfString(100);

        for (int i = 0; i < args.length; i++) {

            fcstack.add(args[i]);

        }

    }



    class FixCapacityStackOfString {


        public FixCapacityStackOfString(int a) {

            list = new String[a];

        }


        private int size;

        private String[] list;



        public int size() {

            return size;

        }


        public boolean isEmpty() {

            if (size == 0) {

                return true;

            } else {

                return false;

            }

        }


        public String push() {

            return list[--size];

        }


        public void add(String s) {

            list[size++] = s;

        }

    }

}

因为它使用 args,我不能将 main 方法移动到公共类中的方法中。我该如何纠正它?


holdtom
浏览 88回答 2
2回答

茅侃侃

这是一个很好的问题,它展示了“静态”关键字的魔力。您的程序可以通过三种方式执行:第一种方式:当类 FixCapacityStackOfString 是嵌套类时。class ClassName{public static void main(String[] args) {&nbsp; &nbsp; ClassName obj = new ClassName();&nbsp; &nbsp; FixCapacityStackOfString fcstack =&nbsp; &nbsp;obj.new FixCapacityStackOfString(100);}class FixCapacityStackOfString {&nbsp; &nbsp; public FixCapacityStackOfString(int a) {&nbsp; &nbsp; &nbsp; &nbsp; list = new String[a];&nbsp; &nbsp; }&nbsp; &nbsp; private int size;&nbsp; &nbsp; private String[] list;&nbsp; &nbsp; }}在这种情况下,调用非静态方法的构造函数需要定义它的类的实例。由于您是从静态方法 main 调用的,因此这就是您必须调用的方式。第二种方式:如果你的类 FixCapacityStackOfString 在主类之外class ClassName&nbsp; &nbsp; {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; FixCapacityStackOfString fcstack =&nbsp; &nbsp;new FixCapacityStackOfString(100);&nbsp; &nbsp; }&nbsp; &nbsp; }class FixCapacityStackOfString {&nbsp; &nbsp; &nbsp; &nbsp; public FixCapacityStackOfString(int a) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list = new String[a];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; private int size;&nbsp; &nbsp; &nbsp; &nbsp; private String[] list;&nbsp; &nbsp; &nbsp; &nbsp; }第三种方式:在第一类中将类 FixCapacityStackOfString 声明为静态。class ClassName{public static void main(String[] args) {&nbsp; &nbsp; FixCapacityStackOfString fcstack = new FixCapacityStackOfString(100);}static class FixCapacityStackOfString {&nbsp; &nbsp; public FixCapacityStackOfString(int a) {&nbsp; &nbsp; &nbsp; &nbsp; list = new String[a];&nbsp; &nbsp; }&nbsp; &nbsp; private int size;&nbsp; &nbsp; private String[] list;&nbsp; &nbsp; }}

DIEA

您的代码如下所示:class TestStack1 {&nbsp; &nbsp; public static void main(String[] args) { ... }&nbsp; &nbsp; class FixCapacityStackOfString { ... }}而你FixCapacityStackOfString在main. 但FixCapacityStackOfString它不是一个静态类:它需要一个TestStack1. 您在静态 main 方法中没有此实例。所以只需声明FixCapacityStackOfString为静态:static class FixCapacityStackOfString { ... }
随时随地看视频慕课网APP

相关分类

Java
我要回答