Classes Objects Instantiation

Topic Progress

Instantiating objects from a class

Task 1

Open Eclipse and creat a new Java project as below

Run the code and experiment with adding a third and fourth lamp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Lamp {
  boolean isOn;

  void turnOn() {
    isOn = true;
  }

  void turnOff() {
   isOn = false;
  }
 
  void displayLightStatus() {
     
     System.out.println("Light on? " + isOn);
  }
}


class ClassObjectsExample {
public static void main(String[] args) {
   
   Lamp l1 = new Lamp(), l2 = new Lamp();
   
   l1.turnOn();
   l2.turnOff();
   
   l1.displayLightStatus();
   l2.displayLightStatus();
  }
}

You are going to create 2 classes called person and createObjects

Run the program in eclipse

Encapsulation



Start a new project in Eclipse called encapsulation and create the two classes as above

Troubleshoot and run the program

What do you notice about the variables and the methods?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Person {

   private String name;
   private String idNum;
   private int age;

   public int getAge(){
      return age;
   }

   public String getName(){
      return name;
   }

   public String getIdNum(){
      return idNum;
   }

   public void setAge( int newAge){
      age = newAge;
   }

   public void setName(String newName){
      name = newName;
   }

   public void setIdNum( String newId){
      idNum = newId;
   }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class CreateObjects{

   public static void main(String args[]){
      Person p1 = new Person();
      Person p2 = new Person();
     
      p1.setName("James");
      p1.setAge(20);
      p1.setIdNum("1234311");
     
      p2.setName("Harry");
      p2.setAge(28);
      p2.setIdNum("1212121");

      System.out.print("Name : " + p1.getName()+
                             " Age : "+ p1.getAge());
     
      System.out.print("Name : " + p2.getName()+
                             " Age : "+ p2.getAge());
    }
}

Extension Activities

  • Add 2 more employees and run
  • Add Set postocode
  • Add Get postcode
  • Add Set favecolour
  • Add Get favecolour
  • Adapt the code so that it includes postcode, favcolour and run

Experimenting with Java in Eclipse

The best way to learn Java is to get example programs running in Eclipse editor or Netbeans

When pasting the example programs you may need to delete line numbers and trouble shoot. Aflter you have done this you can press CTRL SHIFT and F to format the code so it is easier to read

Create a test project, go to the following website where you can find example code to paste and run it in Eclipse

Java Examples