Java 继承报错:子类无法访问父类局部变量的解决方法
public class Rectangle { int length; int wide; public Rectangle(int length, int wide) { this.length = length; this.wide = wide; } public Rectangle() { } //周长 public int perimeter() { return (length+wide)2; } //面积 public int area() { return lengthwide; } } //四棱柱 public class Column extends Rectangle { int height; public Column(int length, int wide, int height) { super(length, wide); this.height = height; } public Column() { } //表面积 public void surfaceArea() { int surfaceArea = perimeter()*height + area()*2; System.out.println("表面积是:"+surfaceArea); } //体积 public void volume() { int volume = area()*height; System.out.println("体积是:"+volume); } } 为什么报错,第二种呢?第二种报错的原因是因为在子类Column中的方法surfaceArea()和volume()中使用了父类Rectangle中的perimeter和area变量,但是这两个变量是父类的方法内部局部变量,子类无法直接访问。解决这个问题的方法是将父类的方法perimeter()和area()改为返回值,并在子类中调用这两个方法来获取对应的值。修改后的代码如下: java public class Rectangle { int length; int wide; public Rectangle(int length, int wide) { this.length = length; this.wide = wide; } public Rectangle() {} // 周长 public int perimeter() { return (length + wide) * 2; } // 面积 public int area() { return length * wide; } } // 四棱柱 public class Column extends Rectangle { int height; public Column(int length, int wide, int height) { super(length, wide); this.height = height; } public Column() {} // 表面积 public void surfaceArea() { int surfaceArea = perimeter() * height + area() * 2; System.out.println("表面积是:" + surfaceArea); } // 体积 public void volume() { int volume = area() * height; System.out.println("体积是:" + volume); } } 这样修改后,子类中的surfaceArea()和volume()方法就能正确地获取父类中的周长和面积了。
原文地址: https://www.cveoy.top/t/topic/pA3S 著作权归作者所有。请勿转载和采集!