Java обекти и класове

Classes edit

Classes are the core of Java. Everything is done within classes. You already know how to create a class:

public class NAME
{

}

You can also have multiple classes in a single file:

public class NAME
{}

class otherClass
{}

When this is compiled two class files will be created, Name.class and otherClass.class.

otherClass can be run by java otherClass just like normal. You can use these classes in objects...

Fields edit

Fields (also known as instance variables) are variables declared in the class itself - not in any method. For example, the following is a field:

class SomeClass
{
   int field;//This was not declared inside any method
}

Fields have many purposes, as they are global variables. They can be accessed from outside the class in objects (see Objects).

Methods edit

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:

public static void main(String[] args)

It has a return type of void - it does not return anything Its parameter is a String array. That String array is what you type after the class. For example, you type: java Class something "something" is stored in the String array. You will learn more about arrays later.

Lastly, just like variables, every method has a identifier and access control (public, private, etc.). Example - protected String getAString()

Now, lets get into return types. The following returns an int: public int returnsInt()

But what does that mean? Well, it means that it must have a return statement within it, and inside the return statement it must have an integer. An example:

public int returnsInt()
{
   return 5;
}

You don't have to put it at the end, as I said.

Would the following work:

public void returnsNothing()
{
   return;
}

The answer, actually, is yes. "return;" means to #1 return nothing #2 terminate the method. All return statements terminate the method. However, do not insert code after the return statement unless if it has a possibility of not going there (i.e., you use a control flow block like "if"). This is useful:

public void returnsNothing(int someNumb)
{
   if(someNumb == 5)
   {
      return;
   }

   someNumb = 1;
}

No else method is needed, though it IS better to use one. This was just to spark some cases where you could use it. Now, lets call a method. Its very simple: returnNothing(5); would be a valid statement. In fact, returnNothing(ANY_INT) is valid. Note that how you call a method and how you create a method are similar. Methods are useful to breakup code (more in Fundamentals End). Methods can call each other. As I said earlier, main is a method. So why, when you say java, does main somehow get started up. The answer is that when you type java, it actually is calling main!

More on parameters... they are useful when you want another method to have a variable, but don't want to use a field, or else you are using objects and don't want to set a field. You declare a variable inside the method's parameter (see the examples).

nested Classes edit

classes can also be added to other classes. These are called nested classes:

public class cl1
{
    private class cl2
      {
      }
}

a nested class can have a nested class or more too.

nested classes act just like normal classes, but they cannot be called from other classes, and they can accses to all variables from same level and higher.

Constructor edit

The constructor of a class is a method that must be called for an object to be initialized. See Object for more information...

This method is different - its syntax is changed. Because it cannot return anything, it has no return statement. Also, the method name is the same as the class name. Here is an example:

class ConstructorTest
{
   public ConstructorTest()
   {
      //doSomething
   }
}

However, it CAN have parameters: public ConstructorTest(String example)

Parameters can be used to say what you want a field to be. Example:

class ConstructorTest
{
   String example;

   public ConstructorTest(String ex)
   {
      example = ex;
   }
}

Exercises edit

1. Make a class with a field - String message, set to "Message" in the class. The main method should call a method called performOp. The performOp method should set the string to "Message2". Name the class Operation.

2. Edit the above class so that the main method sends a string to the performOp method.


Answer to #1.

public class Operation
{
   static String message="Message";

   public static void main(String[] args)
   {
      performOp();
   }

   private static void performOp()
   {
      message="Message2";
   }
}

Answer to #2

public class Operation
{
   public static void main(String[] args)
   {
      performOp("SomeSting");
   }

   private static void performOp(String message)
   {
      System.out.println(message);
   }
}

You may be wondering, if you did not have the "static" part, why your program did not compile. It is because "main" can only run static methods (except for constructors, which in a way are actually static). "static" makes a method OR field be the same even through objects (See Objects). You will get a better understanding of this.

Objects edit

Objects are basically prints of classes that can be changed - or else, instances of classes.

Creating Objects edit

Unlike some object oriented languages, objects are always allocated in the heap and are always created with a new operation. Object variables are references (similar to pointers, but with all of the dangerous parts removed), not instances, and can refer to any object of the declared type.

First you must declare an object reference, like this:

SomeClass SomeObject;//SomeClass is the class, SomeObject is the name of the reference variable

Now, you must initialize it so that it points to an object, like this:

SomeObject = new SomeClass();

The new operation will allocate the memory of an object of type SomeClass and call the class's constructor to initialize that memory. For the 2nd class you created, we can make a constructor and remove the main:

public class Operation
{
   String message="Message";

   public Operation(String mess)
   {
      performOp(mess);
   }

   private void performOp(String message)
   {
      mess;
   }
}

Now, we can create an object to use the constructor:

Operation op;
op=new Operation("STRINGHERE");

We can also do it all on one line:

Operation op=new Operation("STRINGHERE");

This is just like "int i=100", except that we are calling the constructor rather than using a primitive type.

Using Fields and Methods edit

You can also easily use methods/fields in a class. The syntax is:

[object reference].[method/field];

Note: On methods, you still need the parameter.

Now, lets make a String and use the toCharArray method...

String test="T-e+s-t*i2n1g"
Char[] testToChar;
testToChar=test.toCharArray();

Or else, using the Operation class, we can pretend everything is public (meaning it can be accessed from outside the class).

Operation op=new Operation("OPERATION");
op.performOp("OPERATION2");
op.message = "OPERATION3";

Each of these do the same thing except with a different string.

Using Classes in One File edit

If you create multiple classes in one file, you can make objects of them similarly.


Make exercises...

Final Exercise edit

Make a class called Ship that has all the methods we have shown. Suppose each pulse will increase the speed by times*3/2




Answer:

public class Ship
{
   public int speed;//Must be public - its accessed from outside the class

   public Ship()
   {
      speed=0;//You are going at speed of 0 at the dock
   }

   public mainThrustPulse(int times)//Again, must be public
   {
      speed += times*3/2;//Using shorthand form of speed = speed + ...;
   }
}