Unit-III Session 23 Constructors in Subclass
Unit-III Session 23 Constructors in Subclass
UNIT 3
A Java program will automatically create a constructor if it is not already defined in the
program. It is executed when an instance of the class is created.
1. Default constructor
2. Parameterized constructor
OrderofExecution1.java
1. /* Parent Class */
2. class ParentClass
3. {
4. /* Constructor */
5. ParentClass()
6. {
7. System.out.println("ParentClass constructor executed.");
8. }
9. }
10.
11. /* Child Class */
12. class ChildClass extends ParentClass
13. {
14. /* Constructor */
15. ChildClass()
16. {
17. System.out.println("ChildClass constructor executed.");
18. }
19. }
20.
21. public class OrderofExecution1
22. {
23. /* Driver Code */
24. public static void main(String ar[])
25. {
26. /* Create instance of ChildClass */
27. System.out.println("Order of constructor execution...");
28. new ChildClass();
29. }
30. }
Output:
OrderofExecution2.java
1. class College
2. {
3. /* Constructor */
4. College()
5. {
6. System.out.println("College constructor executed");
7. }
8. }
9.
10. class Department extends College
11. {
12. /* Constructor */
13. Department()
14. {
15. System.out.println("Department constructor executed");
16. }
17. }
18.
19. class Student extends Department
20. {
21. /* Constructor */
22. Student()
23. {
24. System.out.println("Student constructor executed");
25. }
26. }
27. public class OrderofExecution2
28. {
Output:
In the above code, an instance of Student class is created and it invokes the
constructors of College, Department and Student accordingly.
OrderofExecution3.java
16. {
17. /* Create instance of the class */
18. System.out.println("Order of constructor execution...");
19. OrderofExecution3 obj = new OrderofExecution3();
20. }
21. }
Output:
In the above code, the parameterized constructor is called first even when the default
constructor is called while object creation. It happens because this keyword is used as
the first line of the default constructor.
OrderofExecution4.java
1. /* Parent Class */
2. class ParentClass
3. {
4. int a;
5. ParentClass(int x)
6. {
7. a = x;
8. }
9. }
10.
11. /* Child Class */
12. class ChildClass extends ParentClass
13. {
14. int b;
15. ChildClass(int x, int y)
16. {
17. /* Accessing ParentClass Constructor */
18. super(x);
19. b = y;
20. }
21. /* Method to show value of a and b */
22. void Show()
23. {
24. System.out.println("Value of a : "+a+"\nValue of b : "+b);
25. }
26. }
27.
28. public class OrderofExecution4
29. {
30. /* Driver Code */
31. public static void main(String ar[])
32. {
33. System.out.println("Order of constructor execution...");
34. ChildClass d = new ChildClass(79, 89);
35. d.Show();
36. }
37. }
Output: