public class Time
{
private int hour;
private int second;
private int minute;
public Time()
{
setHour(0);
setMinute(0);
setSecond(0);
}
public Time(int h, int m, int s)
{
setHour(h);
setMinute(m);
setSecond(s);
}
public void setHour(int h)
{
hour=h;
}
public void setMinute(int m)
{
minute=m;
}
public void setSecond(int s)
{
second=s;
}
public int getHour()
{
return hour;
}
public int getMinute()
{
return minute;
}
public int getSecond()
{
return second;
}
public String toString()
{
String temp=new String();
if( hour<10 )
temp = temp + "0";
temp = temp + hour + ":";
if( minute<10 )
temp = temp + "0";
temp = temp + minute + ":";
if( second<10 )
temp = temp + "0";
temp = temp + second;
return temp;
}
}
This example illustrates a number of principles. The variables hour, minute, andTime a; //a reference a=new Time(12,23,20); //an instance of a Time objectEach instance of the class Time has a copy of these instance variables. They have
import Time;
public class Driver
{
public static void main( String args[] )
{
Time a = new Time();
Time b = new Time(1,34,6);
System.out.println(a.toString());
System.out.println(b.toString());
System.exit(0);
}
}
Even the main method must be defined as a member method of a class. The output of this00:00:00 01:34:06We didnt really have to import the Time class if the Driver and Time classes were located
Since all methods are defined within a class the question of "symbol lookup", that is how
the compiler determines which variable or reference a particular identifier represents,
is very important. The basic rule of thumb is:
public class Test
{
int a=9;
int b=10;
public void f( )
{
int a=20;
System.out.println( Integer.toString(a) );
System.out.println( Integer.toString(b) );
}
}
The output of the piece of code
Test x = new Test();is
20 10We say that within the scope of the function public void f( ) the local variable
The variable modifiers we have learned so far are:
final char ch='y';
double x = Math.PI;Note that, unlike an instance variable, no instance of the class Math needed to be
public class Thing
{
private static int numberOfThings=0;
public Thing()
{
numberOfThings++;
}
public int getNumberOfThings()
{
return numberOfThings;
}
}
public class DriverForThing
{
public static void main( Strings args[] )
{
Thing a = new Thing(); //Constructor called once
Thing b = new Thing(); //Constructor called twice
Thing c = new Thing(); //Constructor called thrice
System.out.println( Integer.toString(a.getNumberOfThings()) );
}
}
The output of the above codes is 3 (thing about why?). I should mention that a class public class Point
{
private double x;
private double y;
public Point(int xCoordinate, int yCoordinate)
{
x=xCoordinate;
y=yCoordinate;
}
final static Point origin = new Point(0,0);
....//More methods can be added
}
The class instance variable origin is static. The only reason I had to give the reference