• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
火磷
Memory will fade,but not notes.
博客园    首页    新随笔    联系   管理    订阅  订阅
this和super关键字

this关键字:

1.引用成员变量

2.通过this(参数列表)调用类的重载的构造方法

3.返回对象的值:使用return this,来返回某个类的引用。

super关键字:

1.super是一个引用,在子类对象中对父类的引用,用于在子类的方法中调用父类已经被重写的方法

2.当父类的构造方法中有参时,子类的构造方法必须使用super(参数值); 对于父类无参的默认构造器,子类会使用默认的super();,可以不写出来

注:this()和super()之前不能写其他语句

Circle.class

public class Circle {
    protected double radius;    
    public Circle(double r) {
        radius=r;
    }
    public void setr(double radius){
        this.radius=radius;               //使用this关键字引用成员变量,前面的this.radius指成员变量
    }    
    public double getr(){
        return radius;
    }    
    public double getarea(){
        return 3.14*radius*radius;
    }
}

 Cylinder.class

 1 public class Cylinder extends Circle {
 2     private double length;    
 3     public Cylinder() {
 4         super(1);            //当父类的构造方法中有参时,必须使用super(参数值);                                   
 5         length=1;
 6     }
 7     public void setl(double length){
 8         this.length=length;
 9     }   
10     public double getl(){
11         return length;
12     }  
13 
14    //通过super调用父类方法
15     public double getarea(){
16         return super.getarea() *2+radius*2*3.14*length;    /*在父类中,radius是protected属性,可在子类中直接调用;如果属性为private,                                                                                             则用通过方法getr()获取半径*/
17     }
18     
19     public double getv(){
20         return super.getarea()*length;   //在子类的方法中使用super.被重写的父类方法对该方法进行调用
21     }    
22 } 

test.class

 1 public class test {
 2     public static void main(String args[]){
 3         Cylinder c=new Cylinder();
 4         System.out.println("圆柱体积为: "+c.getv());
 5         System.out.println("圆柱表面积为: "+c.getarea());
 6         c.setl(2);
 7         c.setr(1);
 8         System.out.println("圆柱体积为: "+c.getv());
 9         System.out.println("圆柱表面积为: "+c.getarea());
10     }
11 }

posted on 2015-07-27 11:24  火磷  阅读(271)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3