this与super关键字

this

this使用的场景一

  • 当属性名与方法的参数名相同的时候,可以使用 this.名称 表示属性名,而使用 名称 表示参数名。
1 String name = "野猫";
2 void setName(String name) {
3 // this.name 代表属性名name
4 // name 代表参数名
5   this.name = name;
6 }
  • 如果参数名与属性名不相同,这样既可以使用this,也可以不用

this使用的场景二

  • 在一个构造器中调用另一个构造器 使用this()
String name;
// 在一个构造器中调用另一个构造器 使用this()
Cat() {
  this("野猫");
}
Cat(String name) {
this.name = name;
}

 

this使用的场景三

  • 返回当前类对象本身。以便使用者进行链式调用(初学者慎用)
<Cat.java>
int age = 0; Cat incr() {   age++;   return this; }

<Test.java>
// 年龄增加 链式调用(初学者不建议使用) cat1.incr().incr().incr().incr(); System.out.println(cat1.age);

 

this使用的场景四

  • 把this作为参数传递到方法中
<Fruit.java>
public class Fruit {
  String name;
  Fruit(String name) {
  this.name = name;
}
// 水果被人吃
void getEated(Man man) {
  man.eat(this);
}
}

<Man.java>
public class Man {   void eat(Fruit fruit) {     System.out.println("man eat " + fruit.name);   } }
<Test.java>
// 水果被人吃 Man man = new Man(); Fruit fruit = new Fruit("apple"); fruit.getEated(man);

 

super

super是关键字。表示当前类父类的引用。


super使用场景一

  • 在子类中访问父类的方法或属性
<Animal.java>
public class Animal {
public void eat() {
System.out.println("Animal eat");
}
}
<Dog.java>
public class Dog extends Animal { public void eat() { System.out.println("Dog eat"); } public void tryeat() { super.eat(); } }

 

Super使用场景二

  • 在子类的构造器中,调用父类的构造器
<Animal.java>
public class Animal {
public Animal() {
System.out.println("Animal Constructor");
}
}
<Dog.java>
public class Dog extends Animal {
public Dog(String name) {
System.out.println("Dog Constructor");
}
public Dog() {
super();
}
}

 

如果一个类中不写任何构造器,相当于

public Cat() {
super();
}

 

如果写了构造器,但其中不写任何super的东西 相当于在第一行插入

super();

 

posted @ 2017-08-01 20:18  CodeCouldCool  阅读(136)  评论(0编辑  收藏  举报