Credits

Friday, July 2, 2010

Creating Java Objects

We can create an instance of a class through the new keyword associated with a certain class. For instance if there exists  a class called TuitionMethod, we can create an object, say myObject so we can freely access the class' methods and fields.

To create an object, we write:

TuitionMethod myObject = new  TuitionMethod();

[+/-] show/hide

/*Sample program on methods
*/
import java.io.*;
public class TuitionMethod {
double tuition;

public static void main(String args[]) throws IOException{
double tunits;
double unitprice;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
TuitionMethod myObject=new TuitionMethod();

System.out.println("Input tuition units:");
String totalunits=br.readLine();
tunits=Double.parseDouble(totalunits);

System.out.println("Input unit price:");
String unitrate=br.readLine();
unitprice=Double.parseDouble(unitrate);
myObject.compute(tunits,unitprice);
System.out.println("Your tuition is "+myObject.compute(tunits,unitprice ));
}


private void compute(double myunits, double uprice)
{ double tuition= myunits*uprice;
return tuition;

}

}

AddThis