java代码后面重写了toString方法为什么可以访问前面一个类的private变量

  • public class Apple {
    private String color;
    private double weight;
    public Apple() {}
    //提供有参数的构造器
    public Apple(String color,double weight) {
    this.color=color;
    this.weight=weight;
    }

    //省略color、weight的srtter和getter方法
    
    
    //重写toString()方法,用于实现Apple对象的“自我描述”
    public String toString() {
        return"一个苹果,颜色是:"+color+",重量是:"+weight;
    }

    }

    public class ToStringTest {
    public static void main(String[]args) {
    Apple a=new Apple("红色",5.68);
    //打印Apple对象
    System.out.println(a);

    }

    }
    输出结果:一个苹果,颜色是:红色,重量是:5.68

    我是萌新啊


素胚勾勒不出你
浏览 633回答 2
2回答

长风秋雁

这输出很正常啊 你用的apple类的对象 当然可以访问本类的私有变量啊

繁星点点滴滴

声明private表示该变量是私有的,只有内部能使用,外部不能使用。toString在该类内部所以可以使用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java