Reputation: 956
What is happening in this code? I want to display the output as "Printing data ASD" without invoking the constructor.
The child class:
package com.javatraining;
public class test1 extends test2{
public static void main(String[] args) {
disp();
}
}
The parent class:
package com.javatraining;
public class test2
{
public static String name;
public test2(){
name="ASD";
}
public static void disp(){
//test2 t=new test2();
System.out.println("Printing data "+name);
}
}
Upvotes: 2
Views: 5018
Reputation: 1
No, Without the creation of an object we cannot invoke a constructor
Upvotes: 0
Reputation: 6335
You don't have to invoke the constructor of parent class at all,
if all you want in your child class is an initialised value of name
class member, then you can do the declaration + initializations in one go as below.
public static String name = "ASD";
The above style makes it clear at a glance how the variable is initialised and it will also print the expected output.
Of course, if the initialization value is different in different constructors, you must do it in the constructor. You can read more about object initialisation in this article.
Upvotes: 0
Reputation: 1190
NO. You can't invoke a constructor without creating an object.
Unless you create object of test2 by test2 = new test2();
, you will get null
in name.
The only way you would have invoked a constructor if it was static, but constructors in Java can't be static. So you have create an object to invoke constructor.
Upvotes: 0
Reputation: 540
public class MainJava extends Test{
public static void main(String[] args){
//Option 1
disp();
//Option 2
name = "ABCD";
disp();
//Option 3
new Test();
disp();
}
}
class Test {
public static String name = "TEMP";
public Test() {
// Will not get called. Unless you create Object
name = "ASD";
}
public static void disp() {
System.out.println("Printing Data " + name);
}
}
Upvotes: 0
Reputation: 3067
Assign a value to the name object of test 2 class. It will work.
public static void main(String[] args) {
test2.name = "ASD";
disp();
}
Upvotes: 1