Add

Objects Do the Work in Java Language

 

When I was a young object, I wasn’t as smart as the objects you have nowadays. Consider, for example, the object in Listing  Not only does this object display itself, the object can also fill itself with values.

A Class with Two Methods

import java.util.Random;

import java.text.NumberFormat;

import static java.lang.System.out;

class BetterAccount {

String lastName;

int id;

double balance;

void fillWithData() {

Random myRandom = new Random();

lastName = “” +

(char) (myRandom.nextInt(26) + ‘A’) +

(char) (myRandom.nextInt(26) + ‘a’) +

(char) (myRandom.nextInt(26) + ‘a’);

id = myRandom.nextInt(10000);

balance = myRandom.nextInt(10000);

}

void display() {

NumberFormat currency =

NumberFormat.getCurrencyInstance();

out.print(“The account with last name “);

out.print(lastName);

out.print(“ and ID number “);

out.print(id);

out.print(“ has balance “);

out.println(currency.format(balance));

}

}

This Is So Cool!

class ProcessBetterAccounts {

public static void main(String args[]) {

BetterAccount anAccount;

for (int i = 0; i < 3; i++) {

anAccount = new BetterAccount();

anAccount.fillWithData();

anAccount.display();

}

}

}

Passing Values to Methods

Think about sending someone to the supermarket to buy bread. When you do this, you say, “Go to the supermarket and buy some bread.” (Try it at home. You’ll have a fresh loaf of bread in no time at all!) Of course, some other time, you send that same person to the supermarket to buy bananas. You say, “Go to the supermarket and buy some bananas.” And what’s the point of all this? Well, you have a method, and you have some on-the-fly information that you pass to the method when you call it. The method is named “Go to the supermarket and buy some. . . .” The on-the-fly information is either “bread” or “bananas,” depending on your culinary needs. In Java, the method calls would look like this:

goToTheSupermarketAndBuySome(bread);

goToTheSupermarketAndBuySome(bananas);

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.