Learning Java/Objects and Classes: Difference between revisions

Content deleted Content added
rvv
Line 1:
=Classes=
Classes are the core of Java. Everything is done within classes. You already know how to create a class:
<pre>
pblicpublic class AMENAME
{
 
}
pblic class AME
</pre>
 
 
 
 
You can also have multiple classes in a single file:
<pre>
public class NAME
{}
 
 
class otherClass
{}
 
</pre>
 
otherClass can be run by <code>java otherClass</code> just like normal. You can use these classes in objects...
 
==Fields==
Fields are variables declared in the class itself - not in any method. For example, the following is a field:
<pre>
 
class SomeClass
{
 
int field;//This was not declared inside any method
}
 
</pre>
 
Fields have many purposes, as they are global variables. They can be accessed from outside the class in objects (see Objects).
==Methods==
You have used one method in each of your programs - main(String[] args). Methods basically contain statements that help finish a purpose. You cannot put all types of statements outside of a method. Methods have a 'parameter'. That is the area between ( and ). Also, they have a return type. For example, a return type of int means that somewhere in the method it returns an Integer (you will understand this as you create and see methods). Methods are also like blocks - they have a { and }. Everything within that is executed when you "call" the method. Lets examine main again:
 
Line 216 ⟶ 219:
public class Ship
{
public int speed;//Must be public - its accessed from outside the class
public Ship()
 
public Ship()
{
speed=0;//You are going at speed of 0 at the dock