My First Object

In this program you'll write a Person class, and then the main file will create Person objects from it.

  1. Go into the CS labs (see this map for details) and log onto a Windows machine.
  2. Start up a new project, called MyFirstObject, with a main class called Main.java. Refer to Lesson 2 if you are unsure how to do this. You do not need to include javabook2.jar in your class files. But be sure to delete TrivialApplication.java and set Main.java as the main file.
  3. In the blank file Main.java, write the following code:
  4. public class Main {
    
    	public static void main(String[] args) {
    		Person p1 = new Person("Ellen");
    		System.out.println("p1 = " + p1);
    
    		Person p2 = null;
    		System.out.println("p2 = " + p2);
    		
    		p2 = p1;
    		System.out.println("p2 = " + p2);
    		
    		Person p3 = new Person("Erin");
    		System.out.println("p3 = " + p3);
    
    		p1 = p3;
    		System.out.println("p1 = " + p1);
    
    		p3 = p2;
    		System.out.println("p3 = " + p3);
    
    		Person p4 = p3;
    		System.out.println("p4 = " + p4);
    
    		p3 = null;
    		System.out.println("p3 = " + p3);
    
    		p4 = p3;
    		System.out.println("p4 = " + p4);
    
    		p1 = p2;
    		System.out.println("p1 = " + p1);
    
    		p2 = p3;
    		System.out.println("p2 = " + p2);
    
    	}
    
    }
    
  5. Create another new blacnk text file, called Person.java, and add it to the project. You should not set it as the main class, since it is not.
  6. In Person.java, type in the following code:
  7. public class Person {
    
    	private String name;
    	
    	public Person(String givenName) {
    		name = givenName;
    	}
    	
    	public String toString() {
    		return name;
    	}
    	
    }
    
  8. Compile and run your program.
  9. Press enter, as the console window says, and the black console window will disappear.