Why create a Wikiversity account?
Learning Java/Objects and Classes
< Learning Java
1.4Nested Classes
2.1Creating Objects
2.2Using Fields and Methods
2.3Using Classes in One File
3Final Exercise
Classes​[​edit source]
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​{}
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 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:
class SomeClass​{ public SomeClass​(); //default constructor private int field; //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 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:
public static void main​(​String​[] args){ int i = 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:
public int returnsInt​()​{ return 5;}
This method has a single statement which simply returns the value 5.
Would the following work:
public void returnsNothing​()​{ 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:
public void returnsNothing​(​int someNum​)​{ 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:
public class Ship{ /** * Instance variable which holds the speed of the ship. * */ private int speed; /** * * Default constructor. */ public Ship(int s) { speed = s; } public int getSpeed​() { return speed; } public void setSpeed​(​int s) { speed = s; } public void accelerate​(​int s) { speed += s; //Add the value of s to speed and set speed equal to this new value. }}public class TestClass​{ public static void main​(​String​[] args) { Ship aShip = new Ship(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 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:
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; }}
Nested Classes​[​edit source]
Classes can also be added to other classes. These are called nested classes:
public class cl1 { private class cl2 { } }
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 source]
Activity: Classes #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.

Activity: Classes #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​(​"SomeString"​); } 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 source]
Objects are basically prints of classes that can be changed - or else, instances of classes.
Creating Objects​[​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:
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​) { message​; }}
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 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...
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 source]
If you create multiple classes in one file, you can make objects of them similarly.

Make exercises...

Final Exercise​[​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

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 + ...; }}

Project: Java
Previous: Java Decision Structures — Learning Java/Objects and Classes — Next: Java Error Handling

Categories: Learning activitiesLearning Java
This page was last edited on 30 October 2020, at 02:46.
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy.
Privacy policy
About Wikiversity
Mobile view
Cookie statement
TalkContributionsCreate accountLog in
ReadEditEdit sourceView history
Visit the main pageMain PageBrowseRecent changesGuided toursRandomHelpDonatePortalColloquiumNewsProjectsSandboxHelp deskWhat links hereRelated changesSpecial pagesPermanent linkPage informationCite this pageCommonsWikibooksWikidataWikinewsWikipediaWikiquoteWikisourceWikispeciesWikivoyageWiktionaryMeta-WikiOutreachMediaWikiWikimaniaCreate a bookDownload as PDFPrintable versionAdd links