Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

method question

 
Grady Jamyson
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Code:
public class Foo
{
int counter = 10;
public void login()
{
int counter = 5;
System.out.println("The Local variable is : " + counter);
}

public void count()
{
System.out.println("The Instance variable is : " + counter);
}

public static void main(String[] args)
{
new Foo().login();
new Foo().count();
}
}

question:
new Foo().login()
new Foo().count()
what is Foo()?
a method?...I don't understand the meaning of Foo().login()
thanks a lot.
 
Ali Gohar
Ranch Hand
Posts: 572
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually Foo() is a contructor of class Foo. Its a special type of method which has no return type and its name is same as class name. In java a constructor is required to instantiate any class. If i don't declare any constructor in the class then a default constructor is always there like in your case, a default constructor is there
Foo(){
}
Now if we declare any customized constructor which takes parameters or so then the default constructor vanishes we create the object using our own defined constructor.
Now to create the object of class Foo you will write the code
Foo any_obj_name = new Foo();
and to call any method of this object just use dot operator and method name.
any_obj_name.login();
In you example these 2 steps are performed in one. Made a new object without any name and then call method on that object.
new Foo().login();
I suggest you to read about constructors and other Object Oriented Concepts.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic