forked from rahulXbarnwal/JavaTutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDog.java
More file actions
61 lines (45 loc) · 1.95 KB
/
Dog.java
File metadata and controls
61 lines (45 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package pets;
import animals.Animal;
public class Dog extends Animal {
public Dog() {
// If you do not explicitly write super() or this() inside a subclass constructor,
// Java automatically inserts super().
super(); // ✅ protected constructor accessible via inheritance
System.out.println("Dog constructor");
}
public void test() {
// ✅ protected method via inheritance
eat();
this.eat();
// ❌ NOT allowed: protected constructor via object creation
// Animal a1 = new Animal();
// ❌ NOT allowed: protected method via superclass reference
// Animal a2 = this;
// a2.eat();
// ✅ allowed: access via subclass reference
Dog d = this;
d.eat();
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.test();
// Output:
// Animal constructor
// Dog constructor
// Animal is eating
// Animal is eating
// Animal is eating
// *V.IMP* -> In a different package, protected members are accessible only through inheritance,
// not through a superclass reference or object creation.
// 1. Java does NOT match constructors by parameter count automatically
// Having a 1-param constructor in subclass does NOT mean Java will call the 1-param constructor in superclass.
// 2. Constructor chaining must be explicit when parameters exist
// 3. super(param) must be the first statement
// TLDR: If a superclass has only parameterized constructors, the subclass must explicitly call super(arguments);
// otherwise, compilation fails.
// If the superclass has a no-argument constructor, Java automatically inserts super()
// even if the subclass constructor has parameters.
// A constructor may contain EXACTLY ONE constructor call (this() OR super()),
// and it must be the FIRST line.
}
}