Reputation: 209
public class Basics {
Basics b = new Basics();
int instanceVariable = 0;
public void behavior() {
System.out.println("Print Something");
}
b.behavior(); // Why this line, b.behavior doesn't work?
public static void main(String[] args){
Basics b = new Basics(); /* Why are we allowed to create an
* object of same name again within
* the same class */
b.behavior(); // This line works
}
}
In the above class, I am able to create object . But I can't call b.behavior
outside any class, but I am able to do that within a method. Why is that so? What is the difference?
public class Basics1 extends Basics{
Basics b = new Basics();
Basics1 b1 = new Basics1();
b = b1.instanceVariable; // I don't see error in this line, but previous line shows //error.
b1.instanceVariable // This line doesn't work
}
Why is b1.instanceVariable
not working, instanceVariable
is the base class instance variable.
Upvotes: 1
Views: 2890
Reputation: 20842
You need to understand that a class is a "type definition", not a code block or sequence of statements.
You cannot just write arbitrary statements in a type definition.
Even so, "b1.instanceVariable"
is not a statement. "b1.instanceVariable"
doesn't mean anything in statement context.
Upvotes: 3
Reputation: 262554
All code needs to be in methods, in field declarations (such as Basics b = new Basics();
in your example) or in "initializer blocks" (which are run as part of constructors or during class initialization).
This is just a syntax rule.
In other languages, you can have this kind of "raw code", to achieve various effects. What do you want to achieve?
Upvotes: 2
Reputation: 2586
Write code anywhere and expect it to execute is a form of procedural programming. In this form , you tend to loose context and soon the code becomes a spaghetti code --> methods getting called anywhere , anytime.
With OOP, you are trained to create objects with well defined methods which have a defined context. Just think, when would you like to get the b.behavior(); being called : Before initializing a class, after initializing the class, after execution of main or when the object is destroyed?
Interestingly, Java has defined syntaxes for each of the states.. You can wrap your code in { System.out.println("Hello World "); } and it will execute when the class is instantiate...Also you can use static { System.out.println("Hello World "); } and this will execute when class is loaded. But again, this is part of telling the JVM when to do it - an agreed upon syntax.. But without any marker around your code, when would you actually expect to run?
Upvotes: 0
Reputation: 2864
A class defines variables and methods. b.behavior(); is a statement that cannot be on its own like that.
Upvotes: 3