You are on page 1of 3

First, in the example below I use "this" as a variable.

We can see that is very useful in this


case because the 2 variables have the same name so by put "this" in the frond we say clearly
that we refer to the variable that is in the class and not the parameters of the constructor.

Second, I use the "super" as a constructor by referring to "super(age, male,


partOfUniversity); in this example, I let the program know that I want to use the constructor
from the superclass that has 3 parameters. this is also very useful because it makes it easy for
the programmer to use the constructors from the parent class. 

Third, I use "super" as a variable by calling the static variable of the class
"super.numberOfStudents". This is also very useful because we might have another variable
with the same name. By putting "super" in the frond we make clear that we want to access the
class level variable. 

1 public class Quiz {


2 public static void main(String[] args) {
3 People mario = new Students(18, true, true);
4 mario.status();
5 System.out.println("Number of Students: " +
6 People.numberOfStudents);
7 }
8 }
9
10 class People {
11 int age;
12 boolean male;
13 boolean partOfUniversity;
14 public static int numberOfStudents = 0;
15
16 public People(int age, boolean male, Boolean partOfUniversity) {
17 // Below i use "this" as a variable.
18 this.age = age;
19 this.male = male;
20 this.partOfUniversity = partOfUniversity;
21 }
22
23
24 public void status() {
25 String sex;
26 String enrolled;
27 if (male == true) {
28 sex = "Male";
29 } else {
30 sex = "Female";
31 }
32
33 if (partOfUniversity == true) {
enrolled = "Part of the University";
} else {
34
enrolled = "Outsider";
35
}
36
System.out.println("Age: " + age + "\nSex: " + sex + "\nStatus:
37
" + enrolled);
38
39
}
40
}
41
42
class Students extends People {
43
44
int age;
45
boolean male;
46
Boolean partOfUniversity;
47
48
49
Students(int age, boolean male, Boolean partOfUniversity) {
50
51
//The "Super" bellow is working as a constructor.
52
super(age, male, partOfUniversity);
53
// The "Super" bellow is working as a variable.
54
super.numberOfStudents++;
55
}
56
}

OUTPUT:

Age: 18

Sex: Male

Status: Part of the University

Number of Students: 1

Finally, in the example below I use "this" as a constructor. This is also a very useful tool
because we can call the constructor with no parameters while we are in another constructor of
the same class.
public class Example2 {
1
String name;
2
Example2(){
3
System.out.println("Welcome!");
4
}
5
Example2(String name){
6
this();
7
this.name=name;
8
System.out.println("Your name is "+ name);
9
}
10
11
public static void main(String[] args){
12
Example2 example=new Example2("Chris");
13
14
}
15
}
16

OUTPUT:

Welcome!

Your name is Chris

You might also like