super Keyword
1. What Is super? (beginner)
super = "my parent!" — access parent's field/method/ctor when child hides it. Twin of this (this=self, super=parent!).
2. Three Uses (exam list + code!)
class Animal {
String name = "Animal";
Animal() { System.out.println("animal born"); }
void eat() { System.out.println("eats food"); }
}
class Dog extends Animal {
String name = "Dog"; // HIDES parent name!
Dog() {
super(); // 1. parent ctor (FIRST line! builds parent part first!)
System.out.println("dog born");
}
void show() {
System.out.println(name); // Dog (own!)
System.out.println(super.name); // Animal (parent's!)
eat(); // own (if overridden, own wins!)
super.eat(); // 2. parent version! (bypass override!)
}
}
3. Rules (traps!)
super()FIRST line of child ctor (else compiler insertssuper()auto — needs no-arg parent!).- No-arg parent missing + child no explicit
super(x)→ ERROR! superin static = ERROR (no parent object!).
4. this vs super (exam table!)
this |
super |
|
|---|---|---|
| Means | self | parent |
| Ctor call | this(...) (sibling!) |
super(...) (parent!) |
| Position | first line | first line |
5. Exam Points
- Three uses + order trace — 5-7 marks, very frequent.
super()first + auto-insert trap — 3-5 marks, frequent.