Tuesday, March 27, 2007

SIMPLE OBJECT BEHAVIOR(1)

SIMPLE OBJECT BEHAVIOR(1)

SNIPPET, java.lang.Object

Every class has Object as a superclass. Object is at the root of the class hierarchy.

If we assume a class that is a subclass of Object, Lagosian, we know every instance of Lagosian has a name and a sex although their orientation might turn out to be different.

This simple example shows what objects are: they have states and behaviour.

package api_package;

public class Lagosian {

//the fields in the class

String name, sex;

//Class constructor, without parameters

Lagosian(){

this.name = "jejecy";

this.sex = "man-woman";

}

//Constructor with parameters

Lagosian(String arg, String orientation){

this.name = arg;

this.sex = orientation;

}

public static void main(String[] args){

//the first object we met at Lagos was tunde

Lagosian firstobject = new Lagosian("tunde", "male");

System.out.println("Tunde: My name is "+

firstobject.name+".");

//The second was a woman, Ngozi

Lagosian secondobject = new Lagosian("ngozi","female");

System.out.println("Ngozi: My name is "+secondobject.name);

//we met a third person who looked like lagbaja

Lagosian thirdperson = new Lagosian();

System.out.println("What is the name of the third

person?");

System.out.println("I answered: his name is

"+thirdperson.name +" and i think he looks like a "+thirdperson.sex);

}

}

In later lessons you’ll learn that we refer to the members of a class by attaching the period . to the name of the object.

Nice day.

No comments: