简单的类的继承的示例

MyPoint.java
 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     }
MyCircle.java
 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 }
TestMyCircle.java
 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(参数);

转载于:https://www.cnblogs.com/hloli/archive/2012/04/11/2442973.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值