0
why print statements cannot be used in class without main but can be used in constructor?
7 Answers
+ 1
import java.util.*;
class Program
{
Scanner s=new Scanner(System.in);
int n,h[];
Program()
{
System.out.println("enter the size of Array:");
n=s.nextInt();
h=new int[n];
System.out.println (n);
}
}
class Main
{
public static void main(String ar[])
{
Program p=new Program();
}
}
0
Could you provide your code if possible?
0
Are you expecting this?
0
Here instead of using print statements in constructor why can't we use in Program class itself
0
Bcoz class is like a blueprint
Blueprints in real life can't do anything unless we don't create objects from those blueprints.
Object is something u can interact with ( not class) and so one cannot expect class to print something but it's object (object are created with constructors) can print
0
You mean why can't you do this?
class something
{
System.out.print("Hello!");
}
0
Yes u can't do that bcoz
Class Is like a blueprint
Irl blueprint of a TV can't do anything alone
We need to create object of that blueprint to do something
And objects are created only with constructors that's why u can print inside constructor and not in the class