java this super实例源码介绍。this关键字表示当前类的实例. 可被用作引用变量(第6行) 或者 方法 (第10行).
[java] view plaincopy
<span style=”font-size:18px;”> 1 class Numbers {
2 private int aNumber = 42;
3
4 public int returnANumber()
5 {
6 return this.aNumber;
7 }
8 public int returnANumber(int intIn)
9 {
10 return (intIn * this.returnANumber());
11 }
12
13 public static void main(String[] args) {
14
15 Numbers numberTest = new Numbers();
16
17 System.out.println(“The Number is ” +
numberTest.returnANumber() );
18 //output is: The Number is 42
19 System.out.println(“The Number is ” +
numberTest.returnANumber(2) );
20 //output is: The Number is 84
21 }
22 }
</span>
super
用于特指引用父类方法
[java] view plaincopy
<span style=”font-size:18px;”>class Cat {
public String name;
public Cat() {name = “no nameIn”;}
public Cat(String nameIn) {name = nameIn;}
public String getName() {
return(name + ” the Cat”);
}
}
class Himalayan extends Cat {
public Himalayan() {}
public Himalayan(String nameIn) {
name = nameIn;
}
public String getName() {
return (name + ” the Himalayan”);
}
public String getNameAsCat() {
return super.getName();
}
public static void main(String[] args) {
Himalayan cappuccino = new Himalayan(“Cappuccino”);
System.out.println(“The Himalayan name is ” +
cappuccino.getName() );
//output is: The Himalayan name is
// Cappuccino the Himalayan
System.out.println(“The Cat name is ”
+ cappuccino.getNameAsCat() );
//output is: The Cat name is
// Cappuccino the Cat
}
}
</span>