简单的类的继承的示例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package point; 2 3 public class MyPoint { 4 5 protected int x; 6 protected int y; 7 8 public MyPoint(){ 9 10 } 11 public MyPoint (int x,int y){ 12 this.x=x; 13 this.y=y; 14 } 15 public void setX(int x) { 16 this.x = x; 17 } 18 public int getX() { 19 return x; 20 } 21 22 public void setY(int y) { 23 this.y = y; 24 } 25 26 public int getY() { 27 return y; 28 } 29 30 31 public String toString (){ 32 return"("+x+","+y+")"; 33 34 } 35 36 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package point; 2 3 public class MyCircle extends MyPoint { 4 protected int radius; 5 6 public MyCircle(){ 7 System.out.println("调用mycircle类的无参数构造方法"); 8 9 } 10 public MyCircle(int x,int y,int radius){ 11 this.x=x; 12 this.y=y; 13 this.radius=radius; 14 15 } 16 public void setRadius(int radius){ 17 if(radius>0) 18 this.radius=radius; 19 } 20 public int getRadius(){ 21 return radius; 22 } 23 public double area (){ 24 return Math.PI*radius*radius; 25 } 26 public String toString(){ 27 return "圆心:"+super.toString()+";半径:"+radius; 28 } 29 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package point; 2 3 import point.MyCircle; 4 public class TestMyCircle { 5 public static void main(String args[]){ 6 MyCircle obj=new MyCircle(10,10,5); 7 System.out.println(obj.toString()); 8 System.out.println("圆的面积:"+obj.area()); 9 10 obj.setX(5); 11 obj.setY(10); 12 obj.setRadius(10); 13 System.out.println(obj.toString()); 14 System.out.println("圆的面积:"+obj.area()); 15 } 16 }
mypoint为父类,mycircle为其子类,子类继承父类之后,对于某些方法需要重写覆盖才能正常使用。
如果要在子类中调用被隐藏的变量,被覆盖的方法只需super一下就行了
super.变量名;
super.方法名;
super(参数);