Intro to Java Objects and Classes

This entry is part 1 of 13 in the series Intro to Java

This lesson will cover some basic concepts in Java related to classes and objects. It was created as a lesson for a class room setting. I have converted it to a post here.

Class vs Object

Definition from page 10, Java A Beginner’s Guide (Herbert Schildt)

A class defines the form of an object. It specifies both the data and the code that will operate on that data. Java uses a class specification to construct objects. Objects are instances of a class. Thus, a class is essentially a set of plans that specify how to build an object.

The code and data that constitute a class are called members of the class. Specifically, the data defined by the class are referred to as member variables or instance variables. The code that operates on that data is referred to as member methods or just methods.

Sun Trails

Index: http://java.sun.com/docs/books/tutorial/index.html

OO Trail: http://java.sun.com/docs/books/tutorial/java/javaOO/index.html

A second look with an example

Lets say you have a blueprint for a robot. Very detailed. It gives very exact detailed diagrams and explanations on how to make a robot. (This is analogous to a class) It tells what parts to use, and how to move the robot. (methods) It even defines that certain bits of memory will be needed to save the location the robot is in (member variables). It also describes how every robot built will have the same model number. (static variable)

Before the robot is built, there is no robot, it doesn’t exist. It is just plans. When someone builds a robot, the plans are transformed (instantiated) into a unique robot. When the robot is built, we might call it bob. While bob is turned on, he is the only robot that knows and keeps track of his location. He could let others know if they asked, but he considers that private information, and only lets other robots that ask politely know where he is. bob does have a model number, but that model number is shared with doug, the other robot that was built the week before.

A third look with code

Let’s look at some code for a robot.

public class Robot extends Object {

	private int location;

	public static final String MODEL_NUMBER = "XRT354";

	public Robot() {
		System.out.println("I am a Robot");
	}

	public int getLocation() {
		return location;
	}

	public void moveUp() {
		location = location + 1;
	}

	public void moveDown() {
		location = location - 1;
	}
}

What is the name of this robot? Is this bob, or doug? What is the location of this Robot? Are these just the blueprints?

Notice that these plans for a Robot extend Object. All classes in Java are Objects. A Robot, or an ArrayList, or a Bird class all build on the work of others. When we acknowledge this work, and say that we want to start with that other class and build on it, and extend its functionality, we use the Java keyword extends.

We also have some modifiers here, private, public, static, and final. Let’s get to those in just a minute. First, let’s meet bob.

To create or build a specific robot, or in Java, instantiate an instance of the Robot class :

Robot bob = new Robot();

And just like that, we have created bob. bob not only knows how to move (moveUp, and moveDown methods) but he also knows his own location. The plans (class) never knew a bob or doug would be created, and they never knew the location of these Robots. They just knew how to describe them.

This is the big item to try to take away from this session. An object is created when you instantiate a class. A class is just plans (no data), but when an object is instantiated, you create an object that has bound its methods and data together. You also need a name to refer to this object, and we happened to call it bob.

Java also likes you to tell it exactly what the right hand, and the left hand should be doing. It needs you to tell it that the variable bob on the left is a Robot, and on the right you say via the “new” that you want to instantiate a Robot.

Why can’t Java just tell the left side what to do based on what the right is doing? Well, a couple of reasons. First, the line could be broken into two, like this:

Robot bob;
bob = new Robot();

This is how Java sees it, not really as one line. Often in our code we will declare our variables in a different place than we assign them.

The second is that this is also a valid statement:

Object bob = new Robot();

Yowsa! How is bob an Object and not a Robot. Because he is both. Look back to the line of code that defines the Robot in our plans. Robot extends Object. This means that a Robot IS A Object. There is not much we can do with an Object, but sometimes it is helpful to do this. We can’t see the moveUp and moveDown methods on bob. Under the covers, a Robot was created, but we told bob that he was an Object, and he believed us, so those methods are not visible.

So what does Object give us? What benefit is there to extending Object? Let’s get to that in a minute.

First, take a look at RobotTest1a.

public class RobotTest1a {

	public static void main(String[] args) {

		Robot bob = new Robot();

		System.out.println("Location:" + bob.getLocation());

		bob.moveUp();

		System.out.println("Location:" + bob.getLocation());
	}
}

Instantiate an Object from a class

It creates a Robot, called bob, prints his location, moves up, and prints his location again.

So what did we do? We took a class, Robot, instantiated it, and assigned it to a variable called bob, of type Robot.

Now lets look at what we can do with our class. What actions can we perform? The actions we can perform, are called methods. What methods are available to the class Robot? There are three that we can see in the Robot class. Is that all? What about the methods from Object?

Getting stuff for free by extending

public class RobotTest1b {

	public static void main(String[] args) {

                Robot bob = new Robot();
		//Object bob = new Robot();

		System.out.println("toString()");
		System.out.println(bob.toString());

		System.out.println("class");
		System.out.println(bob.getClass());
	}
}

The class Robot extends Object, so it inherits all the methods from that class. Let’s look at RobotTest1b. There are lots of methods from Object that we get “for free”. Check out the RobotTest1b. Also look at the sun class Object and see what methods are there. When looking at the Robot class in Eclipse, click on the work Object. Then press F3. This will bring the class Object up in the editor. (you can’t change it, but you can look)

public / private

How about we get back to those public/private things again? RobotTest1c looks at the private member variable location. Can we access the variable directly? Can we modify the Robot code so that we could? Is that a good idea?

public class Robot2 extends Object {

	private int location;

	public static final String MODEL_NUMBER = "XRT354";

	public int getLocation() {
		int aLocation = calculateLocation();
		return aLocation;
	}

	public void moveUp() {
		location = location + 1;
	}

	public void moveDown() {
		location = location - 1;
	}

	/**
	 * A private method that adjusts the location for us.
	 * 
	 * @return
	 */
	private int calculateLocation() {
		return location * 2;
	}
}
public class RobotTest1d {

	public static void main(String[] args) {

		Robot2 bob = new Robot2();

		System.out.println("Location:" + bob.getLocation());
		
		//System.out.println("Location:" + bob.calculateLocation());
	}
}

How about public/private methods? Well, look at Robot2, and RobotTest1d. Here I have added a private method. What does it mean to be private? No one else can see the method other than Robot objects. Why would we do that? Why not make all methods public?

public static final

public class RobotTest1c {

	public static void main(String[] args) {

		Robot bob = new Robot();

		System.out.println("Location:" + bob.getLocation());
		//System.out.println("Location:"+bob.location);
	}
}

Now what about that static final thing? The final part is easy. It just means that the variable cannot be changed. It is a constant. How about the static part? That means that the variable is shared across all the instances of Robot. That is how we get a common part number. We don’t assign this to every robot, it is just part of the plans; the class. This means that we don’t need to ask bob for the value, but we could. See RobotTest1e.

public class RobotTest1e {

	public static void main(String[] args) {

		Robot bob = new Robot();

		System.out.println("Serial#:" + Robot.MODEL_NUMBER);
		System.out.println("Serial#:" + bob.MODEL_NUMBER);
		// Why does the line above work?
		// Why are there two ways to access this?
	}
}

return types

What is a return type. Well, we have already used two. An “int” and a “String”. The return type is what a method returns when you ask a question. When you call getLocation() it returns an int. When we called toString() it returned a String. So, a method can return a primitive, like an int, or it could return an Object, like String. Remember, the return type is not a value. It is the description of what that value will look like. What if you have nothing to return? You give the return type of void, just like in the moveUp() method. Take a look at Robot3 and RobotTest1f.

public class Robot3 extends Object {

	private int location;
	private String mode;

	public static final String MODEL_NUMBER = "XRT354";

	public void setMode(String pMode) {
		mode = pMode;
	}

	public String getMode() {
		return mode;
	}

	public int getLocation() {
		return location;
	}

	public void moveUp() {
		location = location + 1;
	}

	public void moveDown() {
		location = location - 1;
	}
}
public class RobotTest1f {

	public static void main(String[] args) {

		Robot3 bob = new Robot3();

		// here the getLocation() method returns an int
		int aLocation = bob.getLocation();

		// what does this do? is it valid? where does the int go?
		bob.getLocation();

		// why don't we get something back from moveUp()?
		bob.moveUp();

		// why doesn't this work?
		// int aLocation2 = bob.moveUp();
		// what could we change in Robot to make the previous statment valid?
	}
}

Null

What is a null? A null means almost nothing. It means that a variable doesn’t contain an instance of a class. The variable is just a placeholder with no Object in it. When do we get a null pointer exception? We get a null pointer exception when we don’t assign a variable a value, but we try to use it. If no instance is created, there is no data in the object, and there is no way to know what the methods would execute on, so Java throws the null pointer exception. How do we end up with a null? Two ways. We could assign an object the special value of null, then try to execute a method on it. The other is when we take a class, create an instance, and the object is initialized, but we don’t assign the member variables a value. Look at the two member variables in Robot3, location and mode. Location isn’t a problem, because location is an int, and it can’t be null. It automatically becomes 0 on initialization. Mode is an Object, a String, and on initialization it is set to null. See Robot3 and RobotTest1g for an example. This shows what I mean about not getting a variable initialized. How can we protect ourselves from null pointer exceptions? Is there more than one way? See RobotTest1h.

public class RobotTest1g {

	public static void main(String[] args) {

		Robot3 bob = null;

		bob.moveDown();
	}
}
public class RobotTest1h {

	public static void main(String[] args) {

		Robot3 bob = new Robot3();

		// If we run this class aMode becomes null and when we try to execute
		// aMode.toUpperCase() we get the null pointer exception
		String aMode = bob.getMode();
		System.out.println(aMode.toUpperCase());

		// try commenting out the line that gives us a null pointer exception
		// and try this again
		
		// how does this effect the if statement?
		// bob.setMode("operational");

		if (aMode == null) {
			System.out.println("nothing here");
		} else {
			System.out.println(aMode.toUpperCase());
		}
	}
}

Method signatures

This refers to the definition of the method. In Robot3 and RobotTest1h we slipped in a set method that set the mode to some String. This line is called the method signature:

public void setMode(String pMode)

The method is public, meaning it can be accessed by anyone. It has no return type because it says “void”. The method name is “setMode” and it takes in one variable into the method. By convention we have used the letter ‚Äòp’ in front of variables (parameters) that are passed into a method, and ‚Äòa’ for variables local to a method.

Let’s look at Robot4, and RobotTest2a. For this example I have expanded on the setMode() method so that there was more to look at there. In this method we use both the incoming parameter pMode, and the class variable mode. We do a comparison to null, use a method Robot4 gets from Object called equals, and finally assign the new value of pMode to mode (maybe). RobotTest2b shows using the new move methods, and calling private methods.

public class Robot4 extends Object {

	private int location;
	private String mode;

	public static final String MODEL_NUMBER = "XRT354";

	/**
	 * The set mode method signature suggests that this method is public, so
	 * anyone can access it. There is no return value, and it takes in one
	 * variable.
	 * 
	 * This method shows a comparison to null, a comparison to another Object,
	 * and assigning an input value to a class variable.
	 * 
	 * Note: pMode has a scope of the setMode method. It is only useable within
	 * this one method
	 * 
	 * @param pMode
	 */
	public void setMode(String pMode) {
		System.out.println("Current mode:" + mode);
		if (pMode == null) {
			System.out.println("I don't like null Dave.");
			// leave the method with out returning anything
			return;
		}
		if (pMode.equals(mode)) {
			System.out.println("I am already " + mode + " Dave.");
			// leave the method with out returning anything
			return;
		}
		System.out.println("Changing mode to " + pMode);
		mode = pMode;
	}

	public String getMode() {
		return mode;
	}

	public int getLocation() {
		return location;
	}

	/**
	 * Move the robot one step up.
	 */
	public void moveUp() {
		moveTo(location + 1);
		//moveStepUp(); // this works too
	}

	/**
	 * Move the robot one step up.
	 */
	public void moveDown() {
		moveTo(location - 1);
		//moveStepDown(); // this works too
	}

	/**
	 * The moveTo method is used to move the robot one step at a time from it's
	 * current location to a new location. What is the scope of pNewLocation?
	 * What is the scope of aDelta, and aSteps? How about 'i'? It is even more
	 * restricted than the others.
	 * 
	 * @param pNewLocation
	 */
	public void moveTo(int pNewLocation) {
		System.out.println("Moving from " + location + " to " + pNewLocation);
		// calculate how far to go, and what direction?
		int aDelta = pNewLocation - location;
		int aSteps = Math.abs(aDelta);
		for (int i = 0; i < aSteps; i++) {
			//we can use aDelta within the loop
			if (aDelta < 0) {
				moveStepDown();
			}
			if (aDelta > 0) {
				moveStepUp();
			}
		}
		//System.out.println("i is " + i);
		//Why if commented out, does 'i' not exist?
	}

	private void moveStepDown() {
		System.out.println("Move one step down.");
		location = location - 1;
	}

	private void moveStepUp() {
		System.out.println("Move one step up.");
		location = location + 1;
	}
}
public class RobotTest2a {

	public static void main(String[] args) {

		Robot4 aBob = new Robot4();

		aBob.setMode("Operational");
		aBob.setMode(null);
		aBob.setMode("Operational");
		aBob.setMode("Frustrating");
	}
}
public class RobotTest2b {

	public static void main(String[] args) {

		Robot4 aBob = new Robot4();

		aBob.moveUp();
		aBob.moveUp();
		aBob.moveTo(-4);
	}
}

Scope

It is important to understand that the variable pMode only exists within the method setMode. Outside of this method, it doesn’t exist. The class variable mode is useable within any method in the class.

How about the index in a for loop?

for (int i = 0; i < 10; i++) {
  System.out.println("i is " + i);
}

The variable ‘i' only has scope of the loop? Outside of this loop, ‘i' does not exist. Java handles scope by what would be called code blocks. A method is a code block, but it could consist of other code blocks, such as a for loop. The code block is defined with the ‘{‘ and ‘}' brackets. Any variable that is defined within a code block is useable within that code block, and any code block that is contained with it. Any code outside of the code block can not see the variables within the inner code blocks. Take a look at RobotTest2c to see what this looks like.

public class RobotTest2c {

	public static void main(String[] args) {

		Robot4 aBob = new Robot4();

		// can't do this aBabyBob does not exist in this scope
		// aBabyBob.moveUp();

		for (int i = 0; i < 3; i++) {
			Robot4 aBabyBob = new Robot4();
			// aBob is visible because it was created in the code block that
			// contains this one
			aBob.moveUp();
		}

		// aBabyBob is still not visible, it doesn't become visible because it
		// is after the code block that aBabyBob was declared
		// aBabyBob.moveUp();
	}
}

[drain file 1 show tableRow]

[drain file 2 show tableRow]

Type Download Name Version Size Updated Hits
Series NavigationIntro to Java and Static Stuff