0% found this document useful (0 votes)
70 views12 pages

JAVA For Beginners: Using The Vehicle Class

1) The document discusses creating classes and objects in Java. It shows how to define a Vehicle class with properties like passengers and fuel capacity, and then create Vehicle objects and assign them different property values. 2) Methods are introduced as functions within a class that operate on the class's data. Examples show adding a range() method to the Vehicle class to calculate a vehicle's range based on its fuel capacity and mileage. 3) Returning values from methods is covered, including modifying the range() method to return an integer value rather than just printing it. Arguments and parameters are also discussed as a way to pass values into methods.

Uploaded by

shekharc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views12 pages

JAVA For Beginners: Using The Vehicle Class

1) The document discusses creating classes and objects in Java. It shows how to define a Vehicle class with properties like passengers and fuel capacity, and then create Vehicle objects and assign them different property values. 2) Methods are introduced as functions within a class that operate on the class's data. Examples show adding a range() method to the Vehicle class to calculate a vehicle's range based on its fuel capacity and mileage. 3) Returning values from methods is covered, including modifying the range() method to return an integer value rather than just printing it. Arguments and parameters are also discussed as a way to pass values into methods.

Uploaded by

shekharc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

JAVA for Beginners

Note the general form of the previous statement: object.member

Using the Vehicle class


Having created the Vehicle class, let us create an instance of that class:

class VehicleDemo {

public static void main(String args[]) {

Vehicle minivan = new Vehicle();

int range;

// assign values to fields in minivan

minivan.passengers = 7;

minivan.fuelcap = 16;

minivan.mpg = 21;

Till now we have created an instance of Vehicle called ‘minivan’ and assigned values to passengers,
fuel capacity and fuel consumption. Let us add some statements to work out the distance that this
vehicle can travel with a tank full of fuel:

// compute the range assuming a full tank of gas

range = minivan.fuelcap * minivan.mpg;

System.out.println("Minivan can carry " +


minivan.passengers + " with a range of " + range);
}
}

Creating more than one instance


It is possible to create more than one instance in the same program, and each instance would have
its own parameters. The following program creates another instance, sportscar, which has different
instance variables and finally display the range each vehicle can travel having a full tank.

class TwoVehicles {
public static void main(String args[]) {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();

int range1, range2;


// assign values to fields in minivan
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;

Riccardo Flask 73 | P a g e
JAVA for Beginners

// assign values to fields in sportscar


sportscar.passengers = 2;
sportscar.fuelcap = 14;
sportscar.mpg = 12;

// compute the ranges assuming a full tank of gas


range1 = minivan.fuelcap * minivan.mpg;
range2 = sportscar.fuelcap * sportscar.mpg;
System.out.println("Minivan can carry " +
minivan.passengers +
" with a range of " + range1);
System.out.println("Sportscar can carry " +
sportscar.passengers +
" with a range of " + range2);
}
}

Creating Objects
In the previous code, an object was created from a class. Hence ‘minivan’ was an object which was
created at run time from the ‘Vehicle’ class – vehicle minivan = new Vehicle( ) ; This statement
allocates a space in memory for the object and it also creates a reference. We can create a
reference first and then create an object:

Vehicle minivan; // reference to object only


minivan = new Vehicle ( ); // an object is created

Reference Variables and Assignment


Consider the following statements:

Vehicle car1 = new Vehicle ( );

Vehicle car2 = car 1;

We have created a new instance of type Vehicle named car1. However note that car2 is NOT
another instance of type Vehicle. car2 is the same object as car1 and has been assigned the same
properties,

car1.mpg = 26; // sets value of mpg to 26

If we had to enter the following statements:

System.out.println(car1.mpg);

System.out.println(car2.mpg);

The expected output would be 26 twice, each on a separate line.

Riccardo Flask 74 | P a g e
JAVA for Beginners

car1 and car2 are not linked. car2 can be re-assigned to another data type:

Vehicle car1 = new Vehicle();

Vehicle car2 = car1;

Vehicle car3 = new Vehicle();

car2 = car3; // now car2 and car3 refer to the same object.

Methods
Methods are the functions which a particular class possesses. These functions usually use the data
defined by the class itself.

// adding a range() method

class Vehicle {

int passengers; // number of passengers

int fuelcap; // fuel capacity in gallons

int mpg; // fuel consumption in miles per gallon

// Display the range.

void range() {

System.out.println("Range is " + fuelcap * mpg);

Note that ‘fuelcap’ and ‘mpg’ are called directly without the dot (.) operator. Methods take the
following general form:

ret-type name( parameter-list ) {

// body of method

‘ret-type’ specifies the type of data returned by the method. If it does not return any value we write
void. ‘name’ is the method name while the ‘parameter-list’ would be the values assigned to the
variables of a particular method (empty if no arguments are passed).

class AddMeth {

public static void main(String args[]) {

Riccardo Flask 75 | P a g e
JAVA for Beginners

Vehicle minivan = new Vehicle();

Vehicle sportscar = new Vehicle();

int range1, range2;

// assign values to fields in minivan

minivan.passengers = 7;

minivan.fuelcap = 16;

minivan.mpg = 21;

// assign values to fields in sportscar

sportscar.passengers = 2;

sportscar.fuelcap = 14;

sportscar.mpg = 12;

System.out.print("Minivan can carry " +


minivan.passengers + ". ");

minivan.range(); // display range of minivan

System.out.print("Sportscar can carry " +


sportscar.passengers + ". ");

sportscar.range(); // display range of sportscar.

}
}

Returning from a Method


When a method is called, it will execute the statements which it encloses in its curly brackets, this is
referred to what the method returns. However a method can be stopped from executing completely
by using the return statement.

void myMeth() {

int i;

for(i=0; i<10; i++) {

if(i == 5) return; // loop will stop when i = 5

System.out.println();

}
}

Riccardo Flask 76 | P a g e
JAVA for Beginners

Hence the method will exit when it encounters the return statement or the closing curly bracket

There can be more than one exit point in a method depending on particular conditions, but one
must pay attention as too many exit points could render the code unstructured and the program will
not function as desired (plan well your work).

void myMeth() {

// ...

if(done) return;

// ...

if(error) return;

Returning a Value
Most methods return a value. You should be familiar with the sqrt( ) method which returns the
square root of a number. Let us modify our range method to make it return a value:

// Use a return value.

class Vehicle {

int passengers; // number of passengers

int fuelcap; // fuel capacity in gallons

int mpg; // fuel consumption in miles per gallon

// Return the range.

int range() {

return mpg * fuelcap; //returns range for a


particular vehicle

Please note that now our method is no longer void but has int since it returns a value of type
integer. It is important to know what type of variable a method is expected to return in order to set
the parameter type correctly.

Riccardo Flask 77 | P a g e
JAVA for Beginners

Main program:

class RetMeth {

public static void main(String args[]) {

Vehicle minivan = new Vehicle();

Vehicle sportscar = new Vehicle();

int range1, range2;

// assign values to fields in minivan

minivan.passengers = 7;

minivan.fuelcap = 16;

minivan.mpg = 21;

// assign values to fields in sportscar

sportscar.passengers = 2;

sportscar.fuelcap = 14;

sportscar.mpg = 12;

// get the ranges

range1 = minivan.range();

range2 = sportscar.range();

System.out.println("Minivan can carry " +


minivan.passengers + " with range of " + range1 + "
Miles");

System.out.println("Sportscar can carry " +


sportscar.passengers + " with range of " + range2 +
" miles");

Study the last two statements, can you think of a way to make them more efficient, eliminating the
use of the two statements located just above them?

Riccardo Flask 78 | P a g e
JAVA for Beginners

Methods which accept Parameters:


We can design methods which when called can accept a value/s. When a value is passed to a
method it is called an Argument, while the variable that receives the argument is the Parameter.

// Using Parameters.
The method accepts a
class ChkNum { value of type integer, the
parameter is x, while the
// return true if x is even argument would be any
value passed to it
boolean isEven(int x) {

if((x%2) == 0) return true;

else return false;

class ParmDemo {

public static void main(String args[]) {

ChkNum e = new ChkNum();

if(e.isEven(10)) System.out.println("10 is even.");

if(e.isEven(9)) System.out.println("9 is even.");

if(e.isEven(8)) System.out.println("8 is even.");

Predicted Output:

10 is even.

8 is even.

A method can accept more than one parameter. The method would be declared as follows:

int myMeth(int a, double b, float c) {

// ...

Riccardo Flask 79 | P a g e
JAVA for Beginners

The following examples illustrates this:

class Factor {

boolean isFactor(int a, int b) { Note that these


statements are validating
if( (b % a) == 0) return true; ‘x’, and print the correct
else return false; statement.

class IsFact {

public static void main(String args[]) {

Factor x = new Factor();

if(x.isFactor(2, 20)) System.out.println("2 is a


factor.");

if(x.isFactor(3, 20)) System.out.println("this won't be


displayed");

Predicted Output:

2 is a factor.

If we refer back to our ‘vehicle’ example, we can now add a method which works out the fuel
needed by a particular vehicle to cover a particular distance. One has to note here that the result of
this method, even if it takes integers as parameters, might not be a whole number.

Therefore one has to specify that the value that the method returns, in this case we can use
‘double’:

double fuelneeded(int miles) {

return (double) miles / mpg;


}

Riccardo Flask 80 | P a g e
JAVA for Beginners

Updated vehicle class:

class Vehicle {

int passengers; // number of passengers

int fuelcap; // fuel capacity in gallons

int mpg; // fuel consumption in miles per gallon

// Return the range.

int range() {

return mpg * fuelcap;

// Compute fuel needed for a given distance.

double fuelneeded(int miles) {

return (double) miles / mpg;

Main Program:

class CompFuel {

public static void main(String args[]) {

Vehicle minivan = new Vehicle();

Vehicle sportscar = new Vehicle();

double gallons;

int dist = 252;

// assign values to fields in minivan

minivan.passengers = 7;

Riccardo Flask 81 | P a g e
JAVA for Beginners

minivan.fuelcap = 16;

minivan.mpg = 21;

// assign values to fields in sportscar

sportscar.passengers = 2;

sportscar.fuelcap = 14;

sportscar.mpg = 12;

gallons = minivan.fuelneeded(dist);

System.out.println("To go " + dist + " miles minivan


needs " +

gallons + " gallons of fuel.");

gallons = sportscar.fuelneeded(dist); //overwriting same


variable

System.out.println("To go " + dist + " miles sportscar


needs " +

gallons + " gallons of fuel.");

Predicted Output:

To go 252 miles minivan needs 12.0 gallons of fuel.

To go 252 miles sportscar needs 21.0 gallons of fuel.

Riccardo Flask 82 | P a g e
JAVA for Beginners

Project: Creating a Help class from the Help3.java

In order to carry out this task we must examine the Help3.java and identifies ways how we can break
down the code into classes and methods. The code can be broken down as follows:

1. A method which displays the ‘help’ text – helpon( )


2. A method which displays the menu – showmenu( )
3. A method which checks (validates) the entry by the user – isvalid( )

Method helpon( )
void helpon(int what) {

switch(what) {

case '1':

System.out.println("The if:\n");

System.out.println("if(condition) statement;");

System.out.println("else statement;");

break;

case '2':

System.out.println("The switch:\n");

System.out.println("switch(expression) {");

System.out.println(" case constant:");

System.out.println(" statement sequence");

System.out.println(" break;");

System.out.println(" // ...");

System.out.println("}");

break;

case '3':

System.out.println("The for:\n");

System.out.print("for(init; condition; iteration)");

System.out.println(" statement;");

break;

Riccardo Flask 83 | P a g e
JAVA for Beginners

case '4':

System.out.println("The while:\n");

System.out.println("while(condition) statement;");

break;

case '5':

System.out.println("The do-while:\n");

System.out.println("do {");

System.out.println(" statement;");

System.out.println("} while (condition);");

break;

case '6':

System.out.println("The break:\n");

System.out.println("break; or break label;");

break;

case '7':

System.out.println("The continue:\n");

System.out.println("continue; or continue label;");

break;

System.out.println();

Method showmenu( )

void showmenu() {

System.out.println("Help on:");

System.out.println(" 1. if");

System.out.println(" 2. switch");

System.out.println(" 3. for");

Riccardo Flask 84 | P a g e

You might also like