aspose file tools*
The moose likes Beginning Java and the fly likes illegal start of type println Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "illegal start of type println" Watch "illegal start of type println" New topic
Author

illegal start of type println

Daniel Lewis
Greenhorn

Joined: Dec 20, 2011
Posts: 10
Hi folks!
Still learning OOP. Meanwhile I got the feeling that some points are getting clearer, but sometimes -like in the following program, I don't understand, what the problem is:



If I try to compile this I get:
Computer.java:11: error: illegal start of type System.out.println("Hello");

If I remove the System.out.println then it works. So my question is: Why is a println at this position impossible? Using println in methods is ok, but not when defining classes?

Perhaps you can answer me another question too. When i run this program, there is a new notebook object created (by the main class in an other file). Then the methods sell and buy are used "on top" of this object, telling the user "Now you got ... items". Is it possible to get the Name of the object in this println. For example: If it is a notebook Object: Now you got xxx Notebooks, If it is an PC Object: Now you got xxx PCs..."

Thanks in advance!
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3071
    
  33

Your class can have- initialization blocks, variable declarations, methods. But you cannot have other statements within the class. They got to be put inside a block({})


Mohamed Sanaulla | My Blog
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39834
    
  28
System.out.println(...); is a statement.
You are not allowed statements at the “top level” in your class; you ought to put it inside a method or constructor (or an initaliser, but I am not fond of initialiser). Unless you need it for debugging, you ought not to put println statements in constructors.
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
You cannot have printlns directly in the class body - it should be in a method block or so.

Have a instance variable computerType that will hold whether it will be a PC or a desktop, etc. You can assign the variable in the constructor based on the type of computer the object will work on.
Daniel Lewis
Greenhorn

Joined: Dec 20, 2011
Posts: 10
You can assign the variable in the constructor based on the type of computer the object will work on.


So you mean I have to add a variable in my "class Computer" but how can it by "filled" ?

John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
You can use the Computer class' constructor if you knew at object creation on what type the object will be operating like below -
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: illegal start of type println