Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instance methods

 
Ramm Kummar
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to call instance methods from the constructors as stated in this statement from the Kathy's book?

regarding constructor:::
You cannot make a call to an instance method, or access an instance variable,
until after the super constructor runs.

Instance variables can be used inside constructors but how to use methods?
 
Dejan Mratinkovic
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you please be precise what do you need?

You can use instance methods form constructor is if you would from any other method. Only, if you have call to constructor, it has to be first command in method.
 
Ramm Kummar
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1 error) Why void type is not allowed here.
2 error) Why static method call should be first
3) Can we call static methods using object references?

init:
deps-jar:
Compiling 1 source file to C:\Documents and Settings\psbabu\SCJP6\build\classes
C:\Documents and Settings\psbabu\SCJP6\src\scjp6\Animal.java:11: 'void' type not allowed here
this(makeRandomName2());
C:\Documents and Settings\psbabu\SCJP6\src\scjp6\Animal.java:13: call to this must be first statement in constructor
this(makeRandomName());
2 errors
BUILD FAILED (total time: 0 seconds)


 
Dejan Mratinkovic
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

C:\Documents and Settings\psbabu\SCJP6\src\scjp6\Animal.java:11: 'void' type not allowed here
this(makeRandomName2());

1 error) Why void type is not allowed here.


You have a method call (call to constructor of the Animal class) providing a response from void method as parameter.


2 error) Why static method call should be first

C:\Documents and Settings\psbabu\SCJP6\src\scjp6\Animal.java:13: call to this must be first statement in constructor
this(makeRandomName());


Static method call should not be first. About the error, check on wikipedia:

http://java.syntaxerrors.info/index.php?title=Constructor_call_must_be_the_first_statement_in_a_constructor

3) Can we call static methods using object references?


Yes, but not recommended.

Suggestion: Use IDE (I suggest Eclipse, but there are many good IDEs out there). Most of them are smart enough to solve all your problems (by suggesting fixes, etc.)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic