Beginner’s Java: Test Your Knowledge of Classes and Objects

Started programming in Java a few weeks/months ago, but getting horribly confused about classes, objects, settter and getters and this?

This page is for you. If you’re pushed for time you can treat this page as a test and just look at the answers after thinking about them for a bit.

However, for maximum benefit you should try to actually do the exercises. If you get stuck, peek at the answer and then try to do the exercise from memory.

Don’t stress too much about the theory of Java; actually being able to do stuff is the important thing.

A Note on Notation

In this exercise I refer to methods, getters and setters. If you’re following a course on Java and your instructor has just arrived in a time machine from 1990, he might refer to methods as “messages”. Getters might be called “accessors” and setters might be called “mutators”. Probably there’s even worse terminology that I’m not even aware of.

Try not to let this worry you. You may even consider showing your instructor a book from 2011. Perhaps you could also show him how to use mobile phones and WIFI.

1. Create a “Hello World” Program

Create a Java program that simply outputs the text “Hello World” when you run it. Call your main class “Application”.

Show the answer. »

How you do this depends on what development environment (editor) you’re using.

If you’re taking a course, your instructors might make you use some weird development environment. In that case you’ll have to figure this out for yourself.

However, I recommend that you download Eclipse for Java Developers from Eclipse.org and use that. Welcome to the 21st century!

If you need a tutorial on Eclipse, you can find one here.

Your hello world program, if written under normal circumstances, should contain the following code.


public class Application {

	public static void main(String[] args) {
		
			System.out.println("Hello World!");
			
	}

}

Hello World!

2. Create a Class and an Object

In the same file as your main “Application” class, define a new class called “Person”. You don’t need to put anything in the class.

Now, right below where you output “Hello World” in your main method, create an object from that class.

Hint: although you can only have one public class in each file, you can create as many other classes as you want in there, just so long as you don’t use the public keyword with them. Usually of course you put classes in their own files, but here we’ll put our classes in the same file for convenience.

Show the answer. »

class Person {
	
}

public class Application {

	public static void main(String[] args) {
		
			System.out.println("Hello World!");
			
			Person person = new Person();
	}

}

Hello World!

This program doesn’t do anything different from the first one in terms of output, but we are actually defining a new class and creating one object from that class.

3. Basic Constructors

Modify your “Person” class to add a constructor. Make the constructor output the text “Constructor running!”.

Show the answer. »

Since an object’s constructor runs when the object is created, and since we’re already creating a “Person” object here, now we will get some more output.

class Person {
	public Person() {
		System.out.println("Constructor running!");
	}
}

public class Application {

	public static void main(String[] args) {
		
			System.out.println("Hello World!");
			
			Person person = new Person();
	}

}

Hello World!
Constructor running!

4. Multiple Constructors

1. Modify the Person class so that it has another constructor, in addition to the constructor it’s already got. Make this second constructor accept a parameter called name of type String.
2. Make this second constructor print the name parameter using System.out.println().
3. Finally, change your “main” method so that when you create the Person object, you pass in a name. Pass in your own name, in fact.

Show the answer. »

class Person {
	public Person() {
		System.out.println("Constructor running!");
	}
	
	public Person(String name) {
		System.out.println(name);
	}
}

public class Application {

	public static void main(String[] args) {
		
			System.out.println("Hello World!");
			
			Person person = new Person("John");
	}

}

Hello World!
John

Notice that since we’re now calling the second constructor from main, the first constructor no longer runs.

5. Instance Variables, Also Known as Data Members

Modify your Person class so that it has a private instance variable called name of type String.

In your second constructor, set the value of the “name” instance variable using the “name” parameter that you pass in.

Remove the System.out.println()’s from the Person class.

Hint: OK, there’s a problem here. In the constructor there are two variables called “name”. One is a parameter to the constructor, the other is an instance variable. How do you differentiate between them? The answer is to use the keyword this.

This app doesn’t produce much output, but we’ll use what we’ve done in the next exercise.

Show the answer. »

class Person {
	private String name;
	
	public Person() {
	}
	
	public Person(String name) {
		
		// 'this.name' is the instance variable.
		// 'name' is the parameter
		this.name = name;
	}
}

public class Application {

	public static void main(String[] args) {
		
			System.out.println("Hello World!");
			
			Person person = new Person("John");
	}

}

Hello World!

6. Methods

Methods are a way of making subroutines part of objects (by defining them in classes of course).

Add a method to your Person class called “writeName”. Make this method output the text “My name is ” followed by the value of the name instance variable.

Invoke (in other words run or call) this method in your main method.

Your program output should therefore look like the following, assuming your name is “Topsy”.

Hello World!
My name is Topsy

Show the answer. »

class Person {
	private String name;
	
	public Person() {
	}
	
	public Person(String name) {
		
		// 'this.name' is the instance variable.
		// 'name' is the parameter
		this.name = name;
	}
	
	public void writeName() {
		// Note: no 'this' here. 'name' is 
		// not ambiguous so we don't need 'this'.
		System.out.println("My name is " + name);
	}
}

public class Application {

	public static void main(String[] args) {
		
			System.out.println("Hello World!");
			
			Person person = new Person("Topsy");
			person.writeName();
	}

}

7. Get and Set Methods

In prehistoric times, get and set methods (also known as getters and setters) were known as mutators and accessors.

Add getName and setName methods to your class.

Modify your main method like this:

1. Use getName to retrieve the name String from the Person object (in the main method, remember!). Store it there temporarily.
2. Add a space followed by your surname to the String you just retrieved.
3. Use the setName method to set the name instance variable of your person object to the full name that you’ve just created.

Do all this just before calling writeName().

Hint: none of this involves editing the Person class! All your editing should take place in main.

Your program output should now look like this (assuming your surname is “Delores”, and why wouldn’t it be):

Hello World!
My name is Topsy Delores

Show the answer »

class Person {
	private String name;
	
	public Person() {
	}
	
	public Person(String name) {
		
		// 'this.name' is the instance variable.
		// 'name' is the parameter
		this.name = name;
	}
	
	public void writeName() {
		// Note: no 'this' here. 'name' is 
		// not ambiguous so we don't need 'this'.
		System.out.println("My name is " + name);
	}
	
	public void setName(String name) {
		// Use 'this' again to disambiguate.
		this.name = name;
	}
	
	public String getName() {
		// No need for 'this' - not ambiguous here.
		return name;
	}
}

public class Application {

	public static void main(String[] args) {
		
			System.out.println("Hello World!");
			
			Person person = new Person("Topsy");
			
			String name = person.getName();
			name = name + " Delores";
			person.setName(name);
			
			person.writeName();
	}

}

8. Composition

Finally, the challenge to end all challenges. This last question is the bad guy at the end of the level.

1. Above where you defined the person class, define a class called “Brain”.
2. Give the Brain class a constructor.
3. Make the Brain constructor print the text “Thinking…”.
4. Give the Person class a private instance variable of type “Brain”, called “brain”.
3. In the one-parameter Person constructor, set the brain instance variable equal to a new Brain object.

Your program output should now look like the following:

Hello World!
Thinking ...
My name is Topsy Delores

Show the answer. »

class Brain {
	public Brain() {
		System.out.println("Thinking ...");
	}
}

class Person {
	private String name;
	private Brain brain;
	
	public Person() {
		
	}
	
	public Person(String name) {
		
		// 'this.name' is the instance variable.
		// 'name' is the parameter
		this.name = name;
		
		brain = new Brain();
	}
	
	public void writeName() {
		// Note: no 'this' here. 'name' is 
		// not ambiguous so we don't need 'this'.
		System.out.println("My name is " + name);
	}
	
	public void setName(String name) {
		// Use 'this' again to disambiguate.
		this.name = name;
	}
	
	public String getName() {
		// No need for 'this' - not ambiguous here.
		return name;
	}
}

public class Application {

	public static void main(String[] args) {
		
			System.out.println("Hello World!");
			
			Person person = new Person("Topsy");
			
			String name = person.getName();
			name = name + " Delores";
			person.setName(name);
			
			person.writeName();
	}

}

Success?

Once you’re able to do this kind of stuff from memory, you’ve got a decent grasp of the absolute basics of classes and objects in Java. Of course there’s lots more stuff to learn, but this is a great foundation to work from.

Learn to program Java Swing with my complete video course – desktop programming and applets. Includes 7 free videos. Click here for details.

All pages on this site are copyright © 2013 John W. Purcell

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Posted in Java | Tagged , , , , , |