Skip to content

Commit d887f79

Browse files
committed
feat: Add Parent and Child classes to demonstrate constructor chaining in inheritance
WHAT the code does: Defines Parent with a no-argument constructor printing "Parent Constructor". Defines Child extending Parent with a no-argument constructor printing "Child Constructor". Defines ContructorInInheritnce with main(): - Instantiates a Child object. - Output shows constructor call order. WHY this matters: Demonstrates constructor chaining in Java inheritance: - When a subclass object is created, its superclass constructor is called first. - Ensures proper initialization of the inheritance hierarchy. Reinforces that if no explicit super(...) call is provided, Java inserts one automatically. HOW it works: Child c = new Child(): - Calls Parent() constructor first → prints "Parent Constructor". - Then calls Child() constructor → prints "Child Constructor". Demonstrates implicit invocation of superclass constructors. Tips and gotchas: If Parent did not have a no-argument constructor, Child would need to explicitly call super(...) with parameters. Constructors are not inherited but are chained in the object creation process. The class name ContructorInInheritnce contains a typo; should be ConstructorInInheritance. Best practice is to initialize fields in constructors rather than only printing messages. Use-cases: Educational demo of constructor behavior in inheritance hierarchies. Foundation for learning how initialization works in multi-level inheritance. Practical stepping stone toward using super(...) in parameterized constructors. Short key: class-parent-child constructor-chaining inheritance. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent ccb83e0 commit d887f79

File tree

1 file changed

+7
-11
lines changed

1 file changed

+7
-11
lines changed
Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,17 @@
1-
class Parent
2-
{
3-
public Parent()
4-
{
1+
class Parent {
2+
public Parent() {
53
System.out.println("Parent Constructor");
64
}
75
}
8-
class Child extends Parent
9-
{
10-
public Child(){
6+
7+
class Child extends Parent {
8+
public Child() {
119
System.out.println("Child Constructor");
1210
}
1311
}
1412

15-
1613
public class ContructorInInheritnce {
17-
public static void main(String[] args)
18-
{
14+
public static void main(String[] args) {
1915
Child c = new Child();
2016
}
21-
}
17+
}

0 commit comments

Comments
 (0)