Tuesday, March 27, 2007

TYPES, VALUES AND VARIABLES(5)

TYPES, VALUES AND VARIABLES(5)

OPERATORS ON REFERENCE TO OBJECTS:

I want to illustrate some of the features specified in the jls in §4.3.1.

Enjoy.

First a class, Lagosian. Remember. Then we have another class, Nigerian that contains a reference to an instance of a Lagosian. Read the jls, you’ll never lose your way.

package api_package;

public class Lagosian {

//every lagosian has a name, sex and age

String name, sex;

int age;

//Class constructor, he looks like lagbaja

Lagosian(){

this.name = "jejecy";

this.sex = "man-woman";

this.age = 120;

}

//Constructor with parameters, we know am well well

Lagosian(String arg, String orientation, int dperson_age){

this.name = arg;

this.sex = orientation;

this.age = dperson_age;

}

}

package api_package;

public class Nigerian {

//A nigerian must be a lagosian, whether u like it

//or not, to survive.

Lagosian everynigerian;

//apart from being a lagosian, a nigerian is born

//in a town within nigeria

String birthplace = "within nigeria";

//doesn't pay taxes, has no work, doesn't have power supply

boolean taxes = false, employed=false, power=false;

//So to be a nigerian, construct one

Nigerian (Lagosian lagosbobo){

this.everynigerian = lagosbobo;

}

public static void main(String[] args) {

// we want to refer to object Lagosian who is

//called Ngozi. Note that calling the Lagosian

//constructor is a form of method invocation also.

Lagosian ngozi = new Lagosian("ngozi","woman",25);

//let's do field access using qualified names

System.out.print("The age of Ngozi is: ");

System.out.println(ngozi.age); //here!

//let's do field access using field access expansion

System.out.print("Which is lesser than the retirement age

of: ");

System.out.println(Integer.MAX_VALUE+" years");

//make an int become a string with + operator

int stringage = ngozi.age;

System.out.println("We've made it stringed as "+

Integer.toString(stringage)+" years.");

//now the question with instanceof is:

//is ngozi a lagosian?

if(ngozi instanceof Lagosian){

System.out.println("Every nigerian is a lagosian

afterall.");

}else {

System.out.println("Well, we met her in lagos. Can't

say.");

}

//variables can make references to the same object

int outer = ngozi.age;

String sensitive = ngozi.sex;

System.out.println("Ngozi who is a "+ sensitive+" is

"+outer+" years old.");

//let's make ngozi a nigerian by force

Nigerian ourbaby = new Nigerian(ngozi);

//is our baby a nigerian?

System.out.println("Gov: Does she pay her taxes?");

if (ourbaby.taxes){

System.out.println("JJC: Dem don chop her money

without any service.");

}else {

System.out.println("Guyman: Whosai! Where the office

dey for lagos?");

}

}

}

Questions everyone.

No comments: