. Java . Java This and Super
Java This and Super
this
The current class instance.
Can be used with variables (line 6) or methods (line 10).
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 }
super
Used to specify methods in the parent class.
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
}
}
| Comments |
| Sign In |
| to add the first comment for Java This and Super. |