When to use nested class?

こ雲淡風輕ζ 提交于 2020-01-11 09:42:01

问题


The code below will find intersection of 2 lines and return the point object. If point is only ever going to be created by IntersectionOf2Lines class, should i make point a nested class ? If not then why not ? Thanks

class Point {
    private final int x;
    private final int y;

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

    int getX() {
        return x;
    }

    int getY() {
        return y;
    }
}

public class IntersectionOf2Lines {

    public static Point calculateIntersection(Line line1, Line line2) {
        int x = (line2.getConstant() - line1.getConstant()) / (line1.getSlope() - line2.getSlope());
        int y = line1.getSlope() * x + line1.getConstant();

        return new Point(x, y);
    }

回答1:


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;
    }

}



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/17128389/when-to-use-nested-class

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