Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中使用构造函数和新对象_Java_Constructor_Swap - Fatal编程技术网

在Java中使用构造函数和新对象

在Java中使用构造函数和新对象,java,constructor,swap,Java,Constructor,Swap,我得到的方法是点pxy=点(10,20)的未定义错误怎么了?您忘记了新的关键字: public class swap { public class Point { public int x=0; public int y=0; public Point(int a, int b) { this.x = a; this.y = b; }

我得到的方法是
点pxy=点(10,20)的未定义错误怎么了?

您忘记了
新的
关键字:

public class swap
{
    public class Point
    {
        public int x=0;
        public int y=0;

        public Point(int a, int b)
        {
            this.x = a;
            this.y = b;
        }

        public void swapxy(Point p)
        {
            int t;

            t = p.x;
            p.x = p.y;
            p.y = t;
        }

        public String ToString()
        {
            return ("x="+x+" y="+y);
        }
    }


    public static void main(String[] args) 
    {
        Point pxy = Point(10,20);

        pxy.swapxy(pxy);
        System.out.println(pxy);

    }

}

正确的方法:
点pxy=新点(10,20)

要创建实例,请使用'new'关键字

您忘记在“=”后面写新的

正确的方法是这样的:

Point pxy = new Point(10,20);
            ↑↑↑
哦,关键是您要使用的类是Swap的一个内部类,所以您必须在使用它之前实例化它

如果不需要将其放在内部类中,请在单独的文件中声明该类,或者可以按照下面的代码执行:

Point pxy = new Point(10,20);

请重新格式化您的代码。将其复制到编辑器中,按TAB键缩进一次,然后将代码复制回问题中。您有C背景吗?我添加了新的,但仍然出现错误:无法访问swap类型的封闭实例。必须使用swap类型的封闭实例(例如x.new A(),其中x是swap的实例)来限定分配。我编辑了答案,看了看。我添加了“new”,但仍然得到错误:没有可访问的swap类型的封闭实例。必须使用swap类型的封闭实例限定分配(例如x.new A(),其中x是swap实例)。
 public class Swap {
        //add static in the class to access it in a static way
         public static class Point
        {
//change the attributes to private, this is a good practice
            private int x=0;
            private int y=0;

            public Point(int a, int b)
            {
                this.x = a;
                this.y = b;
            }

            public void swapxy(Point p)
            {
                int t;

                t = p.x;
                p.x = p.y;
                p.y = t;
            }

            public String ToString()
            {
                return ("x="+x+" y="+y);
            }
        }

         public static void main(String[] args){

              Swap.Point pxy = new Swap.Point(10,20); 
              System.out.println(pxy.ToString());
         }

    }