When to use nested class?

只谈情不闲聊 提交于 2019-12-01 20:26:42

If the Point class is not needed by any other class and the Point class don't need access to the private class members of IntersectionOf2Lines, then you could make the Point class a static nested class.

A static nested class is a lighter inner class that has no access to the super class members and is often used like structs in C.

package main;

public class Main {

    public static void main(String[] args) {

        MyPoint p = new MyPoint();
        p.x = 5;
        System.out.println("x: "+ p.x);

    }

    private static class MyPoint {
        int x;
    }

}

Mathematically, Line is made of number of points. If you are creating Point class outside, you can use it to show point on particular line, end points of line, so it should be a normal class and not nested class to IntersectionOf2Lines.

If Point is only created by IntersectionOf2Lines, I would implement it as a static nested class: This way you can declare the constructor to be private:

public class IntersectionOf2Lines {
    static class Point {
        private final int x;
        private final int y;

        private Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        int getX() {
            return x;
        }

        int getY() {
            return y;
        }
    }

    public static Point calculateIntersection(int line1, int line2) {
        int x = 1;
        int y = 2;

        return new Point(x, y);
    }

If the constructor is private, the compiler enforces your design/intention.

This is especially useful, if the visibility of the class which contains the result is public (in your example, it's package private), and you do not want that other people instantiate "your" class, because this creates an additional dependency.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!