什么时候使用嵌套类? [英] When to use nested class?

查看:104
本文介绍了什么时候使用嵌套类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码将找到2条线的交点并返回点对象.如果point仅将由IntersectionOf2Lines类创建,那么我应该将point嵌套为类吗?如果不是,那为什么不呢?谢谢

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

推荐答案

如果其他任何类都不需要Point类,并且Point类不需要访问IntersectionOf2Lines的私有类成员,则可以使点类为静态嵌套类.

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.

静态嵌套类是一个较轻的内部类,它无法访问超类成员,并且经常像C语言中的结构一样使用.

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

}

这篇关于什么时候使用嵌套类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆