Anda di halaman 1dari 62

Important Java Reality

A Java program consists of one or more class


declarations.

Every program statement must be placed inside a class.

public class Java0202


{
public static void main (String args[ ])
{
System.out.println("Plain Simple Text Output");
}
}
Program Modules

Program development requires that large


programs are divided into smaller program
modules to be manageable.

This is the principle of divide and conquer.


Structured Programming

Structured Programming is an organized


style of programming that places emphasis
on modular programming, which aids testing,
debugging and modifying.

In structured programming, modules are


procedures and functions that process
external data passed by parameters.
Casual OOP Definition

Object Oriented Programming is a programming


style with heavy emphasis on program reliability
through modular programming.

In object oriented programming, modules contain


both the data and subroutines that process the data.

In Java the modules are called classes and the


process-subroutines are smaller modules called
methods.
Formal OOP Definition

Object Oriented Programming is a style of


programming that incorporates program
development in a language with the following
three OOP traits:

• Encapsulation
• Polymorphism
• Inheritance
OOP
Example
A car could be an object in Java.
Objects have attributes and methods.

Car Attributes Car Methods


Make & Model Drive
Color Park
# of Doors Reverse
# of Seats Tow
Encapsulation

Car Attributes Car Methods


Make & Model Drive
Color Park
# of Doors Reverse
# of Seats Tow

Encapsulation is the process of placing a data


structure’s data (attributes) with the methods
(actions) that act upon the data inside the same
module, called a class in Java.
Inheritance

Inheritance is the process of using features (both


attributes and actions) from an established higher
class. The higher class is called the superclass.
The lower class is called the subclass.

A Truck is a Car with 4WD, big tires, and a bed.


A Limo is a very long luxury Car with many seats.
A Racecar is a Car with 1 seat, a very powerful
engine, and a number painted on the side.
Polymorphism

Polymorphism allows a single accessing


feature, such as an operator, method or class
identifier, to have many forms.

This is hardly a clear explanation. Since the word


polymorphism is used in the formal OOP definition, a brief
explanation is provided, but details of this powerful OOP
concept will come in a later chapter.
Class

A class is a user-defined data type that


encapsulates both data and the
methods that act upon the data.
Object or Instance
An object is one instance of a class.

A class is a type and an object is a variable.

Cat is a class and Fluffy is an object or one instance


of the Cat class.

Objects can be discussed in a general sense, such as


in Object Oriented Programming.

This causes confusion between Object, the concept


and object, the instance of a class.

There is a tendency to use instance when referring to


one variable example of a class.
Attributes or Instance Variables

The data components of a class are


the class attributes and they are
also called instance variables.

Instance variables should only be


accessed by methods of the same
class.
Methods
Methods are action modules that process data.

In other languages such modules may be called


subroutines, procedures and functions.

In Java the modules are called methods.

They are declared inside a class module and


process the instance variables.
Instantiation
Instantiation is the moment or instance that
memory is allocated for a specific object of a class.

Statements like

• the construction of an object


• the definition of an object
• the creation of an object

all have the same meaning as

the instantiation of an object.


// Java1401.java
// Stage-1 of the Person class.
// Only the Person class data attributes are declared.
// Each stage of the Person class will have its own number to
// distinguish between the different stages.

public class Java1401


{
public static void main(String args[])
{
System.out.println("Person Class, Stage 1\n");
Person01 p = new Person01();
System.out.println();
}
}

class Person01
{
String name;
int yearBorn;
int education;
}
Class Declaration Location

In most cases a class declaration is located


outside any other class declaration.

It is possible to declare one class inside


another class (inner class), which will be
explained later.
Instantiation and Construction

An object is created with the new operator.

The creation of a new object is called the:

instantiation of an object
construction of an object

The special method that is called during the


instantiation of a new object is called a
constructor.
// Java1402.java
// Stage-2 of the Person class.
// This stage adds a default "no-parameter" constructor to the Person class.
public class Java1402
{
public static void main(String args[])
{
System.out.println("Person Class, Stage 2\n");
Person02 p = new Person02();
System.out.println();
}
}
class Person02
{
String name;
int yearBorn;
int education;

Person02()
{
System.out.println("Calling Default Constructor");
name = "John Doe";
yearBorn = 1980;
education = 0;
}
}
Constructor Notes
A constructor is a method with the same
identifier as the class.

Constructors are neither void nor return


methods.

A constructor is called during the instantiation


of an object.

Constructors without parameters are default


constructors.
// Java1403.java
// Stage-3 of the Person class.
// This stage accesses Person data directly, which is very poor OOP design
// by violating encapsulation, which may cause side effects.
public class Java1403
{
public static void main(String args[])
{
System.out.println("Person Class, Stage 3\n");
Person03 p = new Person03();
System.out.println("Name: " + p.name);
System.out.println("Born: " + p.yearBorn);
System.out.println("Education: " + p.education);
}
}

class Person03
{
String name;
int yearBorn;
int education;
Person03()
{
System.out.println("Calling Default Constructor");
name = "John Doe"; yearBorn = 1980; education = 0;
}
}
// Java1404.java
// Stage-4 of the Person class.
// In this program direct access to Person data is denied by declaring all class data private.
// This program will not compile.
public class Java1404
{
public static void main(String args[])
{
System.out.println("Person Class, Stage 4\n");
Person04 p = new Person04();
System.out.println("Name: " + p.name);
System.out.println("Year Born: " + p.yearBorn);
System.out.println("Education: " + p.education);
System.out.println();
}
}
class Person04
{
private String name;
private int yearBorn;
private int education;
public Person04()
{
System.out.println("Calling Default Constructor");
name = "John Doe"; yearBorn = 1980; education = 0;
}
}
// Java1405.java
// Stage-5 of the Person class.
// The private data of the Person class is now properly accessed with
// public member "get methods" of the Person class.
public class Java1405
{
public static void main(String args[])
{
System.out.println("Person Class, Stage 5\n");
Person05 p = new Person05();
System.out.println("Name: " + p.getName());
System.out.println("Year Born: " + p.getYearBorn());
System.out.println("Education: " + p.getEducation());
}
}
class Person05
{
private String name;
private int yearBorn;
private int education;
public Person05()
{
System.out.println("Calling Default Constructor");
name = "John Doe"; yearBorn = 1980; education = 0;
}
public int getYearBorn() { return yearBorn; }
public String getName() { return name; }
public int getEducation() { return education; }
}
Private and Public Class Members
The principle of encapsulation requires that object data
members are only accessed by methods of the same object.

Private class members of some object x can only be


accessed by methods of the same x object.

Public class members of some object x can be accessed by


any client of object x.

Data attributes of a class should be declared private.

Methods of a class are usually declared public, but there are


special helper methods that may also be declared private.

Helper methods will be demonstrated later in this chapter.


// Java1406.java Stage-6 of the Person class. This stage adds a second "parameter-constructor" to the Person class.
public class Java1406 {
public static void main(String args[]) {
System.out.println("Person Class, Stage 6\n");
Person06 p1 = new Person06();
System.out.println("Name: " + p1.getName());
System.out.println("Year Born: " + p1.getYearBorn());
System.out.println("Education: " + p1.getEducation());
System.out.println();
Person06 p2 = new Person06("Sue",1972,16);
System.out.println("Name: " + p2.getName());
System.out.println("Year Born: " + p2.getYearBorn());
System.out.println("Education: " + p2.getEducation());
}
}
class Person06 {
private String name;
private int yearBorn;
private int education;
public Person06() {
System.out.println("Calling Default Constructor");
name = "John Doe"; yearBorn = 1980; education = 0;
}
public Person06(String n, int y, int e) {
System.out.println("Calling Parameter Constructor");
name = n; yearBorn = y; education = e;
}
public int getYearBorn() { return yearBorn; }
public String getName() { return name; }
public int getEducation() { return education; }
}
// Java1407.java
// Stage-7 of the Person class.
// This program shows how a program can be separated into multiple files,
// which in this case are the Person07.java and Java1407 files.
// The result is the same as the Java1406.java program.

public class Java1407


{
public static void main(String args[])
{
System.out.println("Person Class, Stage 7\n");
Person07 p1 = new Person07();
System.out.println("Name: " + p1.getName());
System.out.println("Year Born: " + p1.getYearBorn());
System.out.println("Education: " + p1.getEducation());
System.out.println();
Person07 p2 = new Person07("Sue",1972,16);
System.out.println("Name: " + p2.getName());
System.out.println("Year Born: " + p2.getYearBorn());
System.out.println("Education: " + p2.getEducation());
System.out.println();
}
}
// Person07.java This file supports the executable Java1407.java file.
public class Person07
{
private String name;
private int yearBorn;
private int education;
public Person07()
{
System.out.println("Calling Default Constructor");
name = "John Doe";
yearBorn = 1980;
education = 0;
}
public Person07(String n, int y, int e)
{
System.out.println("Calling Parameter Constructor");
name = n;
yearBorn = y;
education = e;
}
public int getYearBorn() { return yearBorn; }
public String getName() { return name; }
public int getEducation() { return education; }
}
Working with Multiple Files
Create a separate file for each class in the
program or at least a file that is manageable in
size with several small classes.

Make sure there is only one file with a main


method, known as the main file.

Place all the files in the same folder and compile


each file separately.

Execute the entire program by executing the


main file.
// Java1408.java Stage-8 of the Person class.
// This stage adds "setMethods" that alter private data of a class during program
// execution. It also adds a showData method to display all the data with a single call.
import java.util.Scanner;
public class Java1408
{
public static void main (String args[])
{
Scanner input = new Scanner(System.in);

System.out.println("Person Class, Stage 8\n");


Person08 p = new Person08();
p.showData();
System.out.print("Enter name ===>> ");
p.setName(input.nextLine());
System.out.print("Enter year born ===>> ");
p.setYearBorn(input.nextInt());
System.out.print("Enter education ===>> ");
p.setEducation(input.nextInt());
System.out.println();

p.showData();
}
}
// Person08.java This file supports the Java1408.java executable file.
public class Person08
{
///// PRIVATE PERSON ATTRIBUTES ////////////////////////////////////////////////////
private String name;
private int yearBorn;
private int education;
///// CONSTRUCTORS ////////////////////////////////////////////////////////////////
public Person08()
{
System.out.println("Calling Default Constructor");
name = "John Doe"; yearBorn = 1980; education = 0;
}

public Person08(String n, int y, int e)


{
System.out.println("Calling Parameter Constructor");
name = n; yearBorn = y; education = e;
}
///// GET (ACCESSOR) METHODS ////////////////////////////////////////////////////////
public String getName() { return name; }
public int getYearBorn() { return yearBorn; }
public int getEducation() { return education; }
public void showData()
{
System.out.println("Name: " + getName());
System.out.println("Year Born: " + getYearBorn());
System.out.println("Education: " + getEducation());
System.out.println();
}
///// SET (MODIFIER) METHODS ////////////////////////////////////////////////////////
public void setYearBorn(int y) { yearBorn = y; }
public void setName(String n) { name = n; }
public void setEducation(int e) { education = e; }
}
// Java1409.java
// Stage-9 of the Person class.
// This stage attempts to create a copy with an existing object
// at the parameter for the constructor of the second object.

public class Java1409


{
public static void main (String args[])
{
System.out.println("Person Class, Stage 09\n");
Person09 p1 = new Person09("Seymour",1975,18);
p1.showData();
Person09 p2 = new Person09(p1);
p2.showData();
}
}
// Java1410.java
// Stage-10 of the Person class.
// This stage attempts to create an copy with an existing object
// at the parameter for the constructor of the second object.
// This time a "copy constructor" has been added to the Person
// class.

public class Java1410


{
public static void main (String args[])
{
System.out.println("Person Class, Stage 10\n");
Person10 p1 = new Person10("Seymour",1975,18);
p1.showData();
Person10 p2 = new Person10(p1);
p2.showData();
}
}
// Person10.java
// This file supports the Java1410.java executable file.
// A portion of the class is shown. The entire class is in your book or on your computer.

public class Person10


{
///// PRIVATE PERSON ATTRIBUTES ////////////////////////////////////////////////////
private String name;
private int yearBorn;
private int education;

///// CONSTRUCTORS ////////////////////////////////////////////////////////////////


public Person10()
{
System.out.println("Calling Default Constructor");
name = "John Doe";
yearBorn = 1980;
education = 0;
}

public Person10(Person10 p)
{
System.out.println("Calling Copy Constructor");
name = p.name;
yearBorn = p.yearBorn;
education = p.education;
}
Copy Constructor
public Person10(Person10 p)
{
System.out.println("Calling Copy Constructor");

name = p.name;
yearBorn = p.yearBorn;
education = p.education;
}
A copy constructor is a constructor that instantiates
a new object as a copy of an existing object.

A copy constructor uses a single parameter, which is


an object of the same class as the copy constructor.
// Java1411.java Stage-11 of the Person class.
// The Person class has been simplified to demonstrate scope of an object.
// The program will only compile with several statements commented out. Remove the
// comments and the program does not compile, because the objects are no longer in scope.
public class Java1411
{
public static void main (String args[])
{
System.out.println("Person Class, Stage 11\n");
System.out.println("MAIN, LEVEL 1");
Person11 p1 = new Person11("Kathy");
p1.showData("p1");
{
System.out.println("\nMAIN, LEVEL 2");
Person11 p2 = new Person11("Joseph");
p2.showData("p2");
{
System.out.println("\nMAIN, LEVEL 3");
p1.showData("p1");
p2.showData("p2");
Person11 p3 = new Person11("Elizabeth");
p3.showData("p3");
}
System.out.println("\nMAIN, LEVEL 2");
p1.showData("p1");
p2.showData("p2");
// p3.showData("p3");
}
System.out.println("\nMAIN, LEVEL 1");
p1.showData("p1");
// p2.showData("p2");
// p3.showData("p3");
}
}
// Java1412.java
// This program demonstrates the side effect caused by the p2 = p1;
// statement. Note that p1 is altered after p2 is altered.
public class Java1412
{
public static void main (String args[])
{
System.out.println("\nJava1412.java\n");
Person p1 = new Person("Kathy");
p1.showData("p1");
Person p2 = new Person("Tom");
p2.showData("p2");
p2 = p1;
p2.showData("p2");
p2.setName("George");
p2.showData("p2");
p1.showData("p1");
System.out.println();
int num1 = 15;
System.out.println("num1: " + num1);
int num2 = 25;
System.out.println("num2: " + num2);
num2 = num1;
System.out.println("num2: " + num2);
num2 = 100;
System.out.println("num2: " + num2);
System.out.println("num1: " + num1);
System.out.println();
}
}
// This class is used with program Java1412.java

class Person
{
private String name;

public Person(String n)
{
name = n;
}

public void showData(String s)


{
System.out.println("showData for: " +
s + " has name " + name);
}

public void setName(String n)


{
name = n;
}
}
// Java1413.java
// This program demonstrates that an object stores the memory address where the
// object data is located. It does not store the data. When one object is assigned
// to another object, the address is copied, not the data.
public class Java1413
{
public static void main (String args[])
{
System.out.println("\nJava1413.java\n");
Person p1 = new Person();
Person p2 = new Person();
System.out.println("p1 value: " + p1);
System.out.println("p2 value: " + p2);
p2 = p1;
System.out.println("\np2 value: " + p2);
System.out.println();
}
}

class Person
{
private String name;
public Person()
{
name = "John Doe";
}
}
What Is Going On? Part 1

p1 p2
@18d107f @3b0eb0

18d107f 3b0eb0
Kathy Tom
What Is Going On? Part 2
p2 = p1;

p1 p2
@18d107f @18d107f

18d107f 3b0eb0
Kathy Tom
What Is Going On? Part 3
p2.setName("George");

p1 p2
@18d107f @18d107f

18d107f 3b0eb0
George Tom
Objects and Simple Data Types
Store Information Differently

Simple (primitive) data types store assigned


values directly in their allocated memory
locations.

Objects store memory references of the


memory locations allocated during the
construction of the object.
Aliasing

Aliasing occurs when two or more variables


reference the same memory location.

Any change in the value of one variable


brings about a change in the value of the
other variable(s).
// Java1414.java
// This program demonstrates the difference between simple, primitive data and objects.
// Simple data passes a value to a method and objects pass a memory address reference to a method.
public class Java1414
{
public static void main (String args[])
{
System.out.println("\nJava1414.java\n");
Person p1 = new Person("Tom");
Person p2 = new Person("Liz");
int intList1[] = {1,2,3,4,5};
int intList2[] = {5,4,3,2,1};
System.out.println("\np1 value: " + p1);
System.out.println("intList1 value: " + intList1);
System.out.println("\np2 value: " + p2);
System.out.println("intList2 value: " + intList2);
System.out.println("\nCalling parameterDemo method");
parameterDemo(7,p1,intList1);
System.out.println("\nCalling parameterDemo method");
parameterDemo(20,p2,intList2);
System.out.println();
}
public static void parameterDemo(int years, Person p, int list[])
{
System.out.println("Parameter years value: " + years);
System.out.println("Parameter p value: " + p);
System.out.println("Parameter list value: " + list);
}
}
class Person
{
private String name;
public Person(String n) { name = n; }
}
// Java1415A.java
// This program demonstrates what happens when simple data types and objects are passed to
// another method (qwerty) as parameters, and those parameters are altered in the method.
// In both cases, while the data is altered inside the qwerty method, the data remains
// unchanged when the qwerty method is finished.
public class Java1415A
{
public static void main (String args[])
{
System.out.println("\nJava1415A.java\n");
int intNum = 100;
String myName = "Bob";
System.out.println("main method values");
System.out.println("intNum: " + intNum);
System.out.println("myName: " + myName);
qwerty(intNum,myName);
System.out.println("\nmain method values");
System.out.println("intNum: " + intNum);
System.out.println("myName: " + myName);
System.out.println();
}
public static void qwerty(int num, String name)
{
num += 100;
name = "Joe";
System.out.println("\nqwerty method values");
System.out.println("num: " + num);
System.out.println("name: " + name);
}
}
// Java1415B.java class Person
// This program demonstrates that when an object {
// is passed as a parameter to a method,
String name;
// any changes to the ATTRIBUTES of that object
// will remain when the method is finished. int age;

public class Java1415B Person(String n, int a)


{
public static void main (String args[]) {
{ name = n;
System.out.println("\nJava1415B.java\n"); age = a;
Person p = new Person("Bob",29); }
System.out.println("main method values");
p.showData(); void alterName(String newName)
qwerty(p); {
System.out.println("\nmain method values"); name = newName;
p.showData(); }
System.out.println();
} void alterAge(int newAge) { age = newAge; }
public static void qwerty(Person p)
{ void showData()
p.alterName("Joe"); {
p.alterAge(37); System.out.println("name: "+name);
System.out.println("\nqwerty method System.out.println("age: "+age);
values");
p.showData(); }
} }
Java Parameters
Java passes information to a method with parameters.

A copy of the calling parameter is assigned to the receiving parameter in


the method.

In the case of a simple/primitive data type, a copy of the variable’s value


(like 23, ‘A’, or true) is what is sent in the parameter. Any changes are
changes to a copy, which has no affect the original.

The same thing actually happens in the case of an object; however, with
an object the value is the memory address of the object itself. If this is
changed, it does not affect the memory address of the original object.

The only way changes made in a method remain after the method is if
the changes are made to the attributes of an object.

NOTE: Strings are objects, even though they tend to behave like
simple/primitive data types in some programs.
The true nature of Strings will be discussed in great detail in Chapter 16.
// Java1416.java
// This program intentionally uses identical parameter identifiers in the constructor method
// as the private attribute identifiers of the Car class. This has an undesirable result.
public class Java1416
{
public static void main (String args[])
{
System.out.println("\nJava1416.java\n");
Car ford = new Car("Explorer",2002,30000.0);
ford.showData();
System.out.println();
}
}
class Car
{
private String make;
private int year;
private double cost;
public Car(String make, int year, double cost)
{
make = make;
year = year;
cost = cost;
}
public void showData()
{
System.out.println("make: " + make);
System.out.println("year: " + year);
System.out.println("cost: " + cost);
}
}
// Java1417.java
// The problem of the previous program is solved by using the "this" reference
// to explicitly indicate the meaning of an identifier.
public class Java1417
{
public static void main (String args[])
{
System.out.println("\nJava1417.java\n");
Car ford = new Car("Explorer",2002,30000.0);
ford.showData();
System.out.println();
}
}
class Car
{
private String make;
private int year;
private double cost;
public Car(String make, int year, double cost)
{
this.make = make;
this.year = year;
this.cost = cost;
}
public void showData()
{
System.out.println("make: " + make);
System.out.println("year: " + year);
System.out.println("cost: " + cost);
}
}
// Java1418.java
// This program introduces the Engine class, which will be used in the next
// program to demonstrate composition.
public class Java1418
{
public static void main(String args[])
{
System.out.println("\nJava1418.java\n");
Engine iForce = new Engine(8,4.7,265);
System.out.println("Cylinders: " + iForce.getCylinders());
System.out.println("Size: " + iForce.getSize());
System.out.println("HorsePower: " + iForce.getHP());
System.out.println();
}
}
class Engine
{
private int cylinders; // number of cylinders in the engine
private double liters; // displacement of the engine in liters
private int horsePower; // horsepower of the engine
public Engine(int cyl, double size, int hp)
{
cylinders = cyl; liters = size; horsePower = hp;
}
public int getCylinders() { return cylinders; }
public double getSize() { return liters; }
public int getHP() { return horsePower; }
}
// Java1419.java
// This program demonstrates "composition", which uses multiple classes in
// such a way that an object of one class become a data member of another class.
public class Java1419
{
public static void main(String args[])
{
System.out.println("\nJava1419.java\n");
Car toyota = new Car("Tundra",4,"Red",8,4.7,265);
toyota.displayCar();
}
}
class Engine // shown on previous slide
class Car
{
private String carMake;
private int carDoors;
private String carColour;
private Engine carEngine;
public Car(String cm, int cd, String cc, int cyl, double size, int hp)
{
carMake = cm; carDoors = cd; carColour = cc;
carEngine = new Engine(cyl,size,hp);
System.out.println("Car Object Finished\n");
}
public void displayCar()
{
System.out.println("carMake: " + carMake);
System.out.println("carDoors: " + carDoors);
System.out.println("carColour: " + carColour);
System.out.println("cylinders: " + carEngine.getCylinders());
System.out.println("size: " + carEngine.getSize());
System.out.println("horsePower: " + carEngine.getHP());
}
}
// Java1420.java
// This program demonstrates the use of static "class"
// methods that do not require the creation of an object.

public class Java1420


{
public static void main(String[] args)
{
System.out.println("\nJava1420.java\n");
System.out.println("100 + 33 = " + Calc.add(100,33));
System.out.println("100 - 33 = " + Calc.sub(100,33));
System.out.println("100 * 33 = " + Calc.mul(100,33));
System.out.println("100 / 33 = " + Calc.div(100,33));
System.out.println();
}
}

class Calc
{
public static double add(double a, double b) { return a + b; }
public static double sub(double a, double b) { return a - b; }
public static double mul(double a, double b) { return a * b; }
public static double div(double a, double b) { return a / b; }
}
// Java1421.java
// This program uses the same Calc class as the previous program. This time an object
// of the Calc class is constructed. This is possible, but not necessary.
public class Java1421
{
public static void main(String[] args)
{
System.out.println("\nJava1421.java\n");
Calc c = new Calc();
System.out.println("100 + 33 = " + c.add(100,33));
System.out.println("100 - 33 = " + c.sub(100,33));
System.out.println("100 * 33 = " + c.mul(100,33));
System.out.println("100 / 33 = " + c.div(100,33));
System.out.println();
}
}
class Calc
{
public static double add(double a, double b) { return a + b; }
public static double sub(double a, double b) { return a - b; }
public static double mul(double a, double b) { return a * b; }
public static double div(double a, double b) { return a / b; }
}
Class Methods
It is possible to access methods directly without first creating
an object. Methods that are accessed in this manner are
called Class Methods.

Class methods need to be declared with the static keyword


used in the heading like:

public static double add(double a, double b)


{
return a + b;
}
Accessing a class method is done with the class identifier,
followed by the method identifier, like:

System.out.println(Calc.add(X,Y));
It is possible to access static methods with object identifiers.
This is considered poor styling and should be avoided.
// Java1422.java
// This program is an example of multiple objects using the same static class attribute. Note
// how the use of object identifiers with object methods and the class identifiers with class methods.
public class Java1422
{
public static void main(String[] args)
{
System.out.println("\nJava1422.java\n");
int newScore;
Game.setHS(1000);
System.out.println("Starting with default high score of 1000\n");
Game p1 = new Game("Tom");
System.out.println(p1.getName() + "'s score is " + p1.getScore() +
" compared to " + Game.getHS() + " high score\n");
newScore = p1.getScore();
if (newScore > Game.getHS()) Game.setHS(newScore);
Game p2 = new Game("Sue");
System.out.println(p2.getName() + "'s score is " + p2.getScore() +
" compared to " + Game.getHS() + " high score\n");
newScore = p2.getScore();
if (newScore > Game.getHS()) Game.setHS(newScore);
Game p3 = new Game("Lois");
System.out.println(p3.getName() + "'s score is " + p3.getScore() +
" compared to " + Game.getHS() + " high score\n");
newScore = p3.getScore();
if (newScore > Game.getHS()) Game.setHS(newScore);
System.out.println("Highest score is " + Game.getHS());
System.out.println();
}
}
// This class is used with program Java1422.java from the previous slide.

class Game
{
private static int highScore; // highest score of any game played
private int score; // current object score
private String player; // name of the current player

public Game(String Name)


{
player = Name;
playGame();
}

public String getName() { return player; }


public static int getHS() { return highScore; }
public int getScore() { return score; }

public void playGame()


{
score = (int) (Math.random() * 10000);
}

public static void setHS(int newScore)


{
highScore = newScore;
}
}
// Java1423.java
// This program uses static attributes and static methods to store school
// budget information and object attributes and object methods to store department information.
public class Java1423
{
public static void main(String[] args)
{
System.out.println("\nJava1423.java\n");
Budget.setSchoolBalance(100000);
System.out.println("Starting school balance: " + Budget.getSchoolBalance() + "\n");
Budget b1 = new Budget("English",20000);
Budget b2 = new Budget("Math",15000);
Budget b3 = new Budget("Comp Science",6000);
System.out.println();
b1.setDeptBalance(-5000);
System.out.println("Deduct 5000 from English");
System.out.println(b1.getDeptBalance() + " left in " + b1.getDeptName());
System.out.println(Budget.getSchoolBalance() + " left in school budget\n");
System.out.println("Deduct 8000 from Math");
b2.setDeptBalance(-8000);
System.out.println(b2.getDeptBalance() + " left in " + b2.getDeptName());
System.out.println(Budget.getSchoolBalance() + " left in school budget\n");
System.out.println("Deduct 9000 from Comp Science");
b3.setDeptBalance(-9000);
System.out.println(b3.getDeptBalance() + " left in " + b3.getDeptName());
System.out.println(Budget.getSchoolBalance() + " left in school budget\n");
}
}
// This class is used with program Java1423.java from the previous slide.

class Budget
{
private static int schoolBalance; // money left in school budget
private int deptBalance; // money left in department budget
private String deptName; // stored department name

public Budget (String dn,int db)


{
deptBalance = db;
deptName = dn;
System.out.println("Constructing " + dn + " object with " + db);
}

public static void setSchoolBalance(int amount) { schoolBalance += amount; }


public static int getSchoolBalance() { return schoolBalance; }
public String getDeptName() { return deptName; }
public int getDeptBalance() { return deptBalance; }
public void setDeptBalance(int amount)
{
deptBalance += amount;
setSchoolBalance(amount);
}
}
Static Methods and Attributes

Static methods and static attributes can be


accessed for the entire duration of a program.

Static variables (attributes) can be accessed by


static methods and object methods.

Instance variables (attributes) can only be


accessed by object methods.

Static attributes can be accessed with object


identifiers and class identifiers.
// Java1424.java
// A series of fishes is drawn on a two-dimensional fishtank grid.
// The file FishGfx.class must be in the same folder as this file for the program to compile.
// Students can use the methods of the FishGfx class, even if they do not understand how they work.
// This program needs top be viewed in 1024 X 768 resolution.import java.awt.*;
public class Java1424 extends java.applet.Applet
{
public void paint(Graphics g)
{
FishGfx f = new FishGfx(g,20,20,4000);
int count = 1;
int clr = 1;
for (int col = 0; col < 20; col++)
{
f.drawFish(g,col,col,clr,count);
count++; clr++;
if (clr > 9) clr = 1;
f.drawFish(g,col,19-col,clr,count);
count++; clr++;
if (clr > 9) clr = 1;
}
for (int col = 0; col < 20; col++)
{
f.eraseFish(g,col,col);
f.eraseFish(g,col,19-col);
}
}
}
// FishGfx.java
// This is a partial source code file of the FishGfx class.
// Only the available method headings are shown. All implementations are hidden.
import java.awt.*;
class FishGfx
{
private void delay(double n)
// This method delays program execution where n is roughly the number of mili-seconds
// of the delay. This method is called after drawFish and eraseFish.
// The only purpose of this method is to view the fish as they are drawn and erased.

private Color getColor(int clr)


// returns the following colors for integer parameter clr:
// 1 red; // 2 green; // 3 blue;
// 4 orange; // 5 cyan; // 6 magenta;
// 7 yellow; // 8 pink; // 9 black;

private void drawGrid(Graphics g, int l, int w)


// draws a two-dimensional grid with l x w (length x width) fish locations

public FishGfx(Graphics g, int rows, int cols, double td)


// constructs a fishgfx object with specified dimensions and time delay (td)

public void drawFish(Graphics g, int row, int col, int clr, int num)
// draws a fish at the specified [row][col] grid location with color (clr) and a number(num)
// to identify the fish

public void eraseFish(Graphics g, int row, int col)


// erases a fish at the specified row Xcol grid location
// an intentional time delay is called at the conclusion