zoukankan      html  css  js  c++  java
  • 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 }

  • 相关阅读:
    智能汽车无人驾驶资料调研(一)
    Python 学习
    关于中英文排版的学习
    UI Testing
    项目管理:第一次参与项目管理
    自动化测试用什么语言好
    什么是自动化测试
    睡眠的重要性
    python的pip和cmd常用命令
    矩阵的切片计算(截取)
  • 原文地址:https://www.cnblogs.com/jfl-xx/p/4679380.html
Copyright © 2011-2022 走看看