super和this的用法

来源:互联网 发布:淘宝客怎么找免单商品 编辑:程序博客网 时间:2024/05/23 19:17

1.super  

       一般是用于子类调用父类的成员和子类的构造函数调用父类的构造函数

1.1   super.

       在子类的一般方法中可以用super.来调用父类的成员变量和成员函数,虽然父类的成员,子类的对象可以直接调用,但是当子类方法对父类的方法进行扩展时,父类中的方法通过super.可以直接调用,然后再扩充想要补充的功能,此时的super.相当于子类的一个对象,这样做的好处是可以降低代码的耦合度和安全性,增强代码复用性.

public class Mamal {public void eat(){System.out.println("chi");}}
public class Whale extends Mamal{public void eat(){super.eat();System.out.println("pai shui");}}
1.2  super()

       只能使用在子类的构造函数中的第一行来调用父类的构造函数.构造函数不同于一般的成员函数,必须明确一点,子类中构造函数必须要调用父类中的构造函数.一个类中,如果没有定义构造函数,那么实际上它会自动生成一个无参的隐式的构造函数,如果自己定义了那么这个无参的隐式的构造函数就会消失,并且对于一个构造函数,其第一行实际上是一行无参的super()的隐式调用方法,同理,如果你自己有定义,那么这个隐式的会消失,所以,对于父类而言,必须要有一个构造函数存在,不然编译会出错.(如果父类定义了一个有参的构造函数,此时无参的消失,子类的隐式构造函数的隐式super()就找不到调用函数,需要自己定义)

public class Pet {protected int age;protected String name;public void eat(){System.out.println("吃");}public Pet(int age,String name){this.age=age;this.name=name;}public Pet(){//无参的构造函数如果没有会编译出错}}
<span style="font-size:18px;">public class Dog extends Pet {public void keepHouse(){super.eat();System.out.println("keep house");}}

2.  this 指代当前对象,调用该方法的对象.

1.1 this

      单独使用时,用来作为一个返回值,返回类型为一个类

1.2 this.

      在setter函数中,如果形参和成员同名,此时实参的值不会传递到调用对象的成员上,因为有一个就近原则,所以为了区别这一情况,用this.指代当前的对象,就可以将实参的值传递给对象,当形参和成员变量不同名的时候,一般不需要加this.,实际上,是省略了this..(this.也可在方法中调用其他方法,不过不常用,实际上是省略了this.)

public class Person {private int age;private double height;public void setAge(int age){//age=age; 两个都是局部变量this.age=age;//将局部变量的age赋值给属性//this是对象,this.weight指的是属性}public Person setHeight(double height){this.height=height;return this;}}
1.2  this()

      用于同一类中不同构造函数调用,必须指出,参数必须要相同才能调用

public class Human {private double  weight;private double height;private int age;public Human(double weight, double height, int age) {this(56.5,178.0);this.age = age;}public Human(double weight, double height) {this(178);this.height = height;}public Human(double weight) {this();this.weight = weight;}public Human() {}}


 

    

      

0 0
原创粉丝点击