Learning Java/Objects and Classes
Classes
[edit | edit source]Classes are the core of Java. Everything is done within classes. You already know how to create a class:
publicclassNAME{}
You can also have multiple classes in a single file:
publicclassNAME{}classotherClass{}
If you do this, only one public class is allowed and the others have to be protected-private (no modifier). 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 | edit source]Fields (also known as instance variables) are variables declared in the class itself - not in any method. For example, the following is a field:
classSomeClass{publicSomeClass();//default constructorprivateintfield;//instance variable}
Fields are like any other variable; they may hold primitive types (int, boolean, double, etc) or reference types (String, Integer, or any other class type). Fields can be accessed outside of the class depending on the visibility modifier they are defined with. In the example above "field" has an access modifier of private, which means that it may only be accessed from within the class itself, and may not be accessed directly outside of the class. We will touch on access modifiers later on.
Methods
[edit | edit source]You have used one method in each of your programs - main(String[] args). Methods are blocks of code which allow classes and objects to perform specific tasks. Methods are defined with an (optional) visibility modifier (such as public or private), an (optional) access modifier (final, static, abstract, etc), a return type (void, int, String, etc) which defines the type of value the method will give after being called, a name, zero or more parameters (inputs), and optionally a throws clause which defines exceptions which the method may throw (Exceptions are discussed later on.). Methods also contain a body, which contains any number of statements to be executed when the method is called.
Lets examine main again:
publicstaticvoidmain(String[]args){inti=0;i++;}
Its visibility is public, which means it can be called outside of the class. Its access modifier is static (more on this later). It has a return type of void - it does not return anything. Its name is main. It takes one parameter, an array of String objects. Finally its body contains two statements.
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 which must return an integer value. An example:
publicintreturnsInt(){return5;}
This method has a single statement which simply returns the value 5.
Would the following work:
publicvoidreturnsNothing(){return;}
The answer, actually, is yes because the return type in this case is "void" which means the method returns nothing.
Return statements terminate execution of the method, so any statements below the return statement will not execute. You can however place the return statement within a conditional block of code, so that if the condition is not met the block of code may be skipped and execution of the method will continue immediately after the conditional block. Consider the following code:
publicvoidreturnsNothing(intsomeNum){if(someNum==5){return;}someNum=1;}
If the parameter someNum equals five the method will exit. Otherwise it will continue to the next line of code immediately after the if block. A single line of code is executed in this case: someNum = 1;
. This is a rather simplified example, however it illustrates how the return statement may be placed in various locations within the method.
Methods are quite simple to call, and you have already seen several examples of method calls in the previous lessons. The code below illustrates how to call a method defined within a class:
publicclassShip{/** * Instance variable which holds the speed of the ship. * */privateintspeed;/** * * Default constructor. */publicShip(ints){speed=s;}publicintgetSpeed(){returnspeed;}publicvoidsetSpeed(ints){speed=s;}publicvoidaccelerate(ints){speed+=s;//Add the value of s to speed and set speed equal to this new value.}}publicclassTestClass{publicstaticvoidmain(String[]args){ShipaShip=newShip(5);//The ship now has a speed of 5.aShip.accelerate(5);//The ship now has a speed of 10.}}
The code above defines two classes: Ship and TestClass. Ship has a number of methods defined, including one called accelerate which adds an integer value to its speed. TestClass contains the main method in which we can create an instance of the Ship class. Once we have an instance we can then call its methods to manipulate its data. We do this by calling using the form: class/object.methodname(). The important thing to notice here is the use of the "." (dot) operator, which is how instance variables and methods are accessed in Java.
Constructor
[edit | edit source]The constructor of a type 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:
classConstructorTest{publicConstructorTest(){//doSomething}}
However, it CAN have parameters: public ConstructorTest(String example)
Parameters can be used to say what you want a field to be. Example:
classConstructorTest{Stringexample;publicConstructorTest(Stringex){example=ex;}}
Nested Classes
[edit | edit source]Classes can also be added to other classes. These are called nested classes:
publicclasscl1{privateclasscl2{}}
A nested class can have one or more nested classes as well.
Nested classes act just like normal classes, but they cannot be called from other classes. Furthermore, they have access to all variables within the containing classes.
Exercises
[edit | edit source]![]() | Activity: Classes #2 |
Edit the above class so that the main method sends a string to the performOp method. |
Answer to #1.
publicclassOperation{staticStringmessage="Message";publicstaticvoidmain(String[]args){performOp();}privatestaticvoidperformOp(){message="Message2";}}
Answer to #2
publicclassOperation{publicstaticvoidmain(String[]args){performOp("SomeString");}privatestaticvoidperformOp(Stringmessage){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 | edit source]Objects are basically prints of classes that can be changed - or else, instances of classes.
Creating Objects
[edit | edit source]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:
SomeClasssomeObject;//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=newSomeClass();
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:
publicclassOperation{Stringmessage="Message";publicOperation(Stringmess){performOp(mess);}privatevoidperformOp(Stringmessage){message;}}
Now, we can create an object to use the constructor:
Operationop;op=newOperation("STRINGHERE");
We can also do it all on one line:
Operationop=newOperation("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 | edit source]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...
Stringtest="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).
Operationop=newOperation("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 | edit source]If you create multiple classes in one file, you can make objects of them similarly.
Make exercises...
Final Exercise
[edit | edit source]![]() | Activity: Final |
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:
publicclassShip{publicintspeed;//Must be public - its accessed from outside the classpublicShip(){speed=0;//You are going at speed of 0 at the dock}publicmainThrustPulse(inttimes)//Again, must be public{speed+=times*3/2;//Using shorthand form of speed = speed + ...;}}
Project:Java |
Previous:Java Decision Structures — Learning Java/Objects and Classes — Next:Java Error Handling |
|