64

Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

Embed Size (px)

Citation preview

Page 1: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class
Page 2: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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"); }}

Page 3: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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.

Page 4: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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.

Page 5: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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.

Page 6: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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

Page 7: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

Encapsulation

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.

Page 8: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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.

Page 9: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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.

Page 10: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

Class

A class is a user-defined data type that encapsulates both data and the methods that act upon the data.

Page 11: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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.

Page 12: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public 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.

Page 13: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public 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.

Page 14: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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.

Page 15: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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;}

Java1401.java Output

Person Class, Stage 1

Page 16: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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.

Page 17: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

Instantiation and Construction

An object is created with the new operator. The creationof a new object is called:

instantiation of an objectconstruction of an object

The special method that is called during the instantiation of a new object is called a constructor.

Page 18: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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; } }

Java1402.java Output

Person Class, Stage 2

Calling Default Constructor

Page 19: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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.

Page 20: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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; }}

Java1403.java Output

Person Class, Stage 3

Calling Default ConstructorName: John DoeBorn: 1980Education: 0

Page 21: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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; } }

Java1404.java Output

Java1404.java:28: Name has private access in Person04 System.out.println("Name: " + P.Name); ^Java1404.java:29: YearBorn has private access in Person04 System.out.println("Year Born: " + P.YearBorn); ^Java1404.java:30: Education has private access in Person04 System.out.println("Education: " + P.Education); ^3 errors

Page 22: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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; }}

Java1405.java Output

Person Class, Stage 5

Calling Default ConstructorName: John DoeYear Born: 1980Education: 0

Page 23: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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.

Page 24: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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; }}

Java1406.java Output

Person Class, Stage 6

Calling Default ConstructorName: John DoeYear Born: 1980Education: 0

Calling Parameter ConstructorName: SueYear Born: 1972Education: 16

As programs get bigger, files can get quite large and tedious. The next slide shows how to handle this.

Page 25: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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(); } }

Java1407.java Output

Person Class, Stage 6

Calling Default ConstructorName: John DoeYear Born: 1980Education: 0

Calling Parameter ConstructorName: SueYear Born: 1972Education: 16

Page 26: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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; }}

Java1407.java Output

Person Class, Stage 6

Calling Default ConstructorName: John DoeYear Born: 1980Education: 0

Calling Parameter ConstructorName: SueYear Born: 1972Education: 16

Page 27: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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 eachfile separately.

Execute the entire program by executing the main file.

Page 28: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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.io.*;

public class Java1408{ public static void main (String args[]) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Person Class, Stage 8\n"); Person08 p = new Person08(); p.showData(); System.out.print("Enter name ===>> "); p.setName(input.readLine()); System.out.print("Enter year born ===>> "); p.setYearBorn(Integer.parseInt(input.readLine())); System.out.print("Enter education ===>> "); p.setEducation(Integer.parseInt(input.readLine())); System.out.println(); p.showData(); } }

Java1408.java Output

Person Class, Stage 8

Calling Default ConstructorName: John DoeYear Born: 1980Education: 0

Enter name ===>> "Byron Derry"Enter year born ===>> 1966Enter education ===>> 20Name: "Byron Derry"Year Born: 1966Education: 20

Page 29: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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; }}

Java1408.java Output

Person Class, Stage 8

Calling Default ConstructorName: John DoeYear Born: 1980Education: 0

Enter name ===>> "Byron Derry"Enter year born ===>> 1966Enter education ===>> 20Name: "Byron Derry"Year Born: 1966Education: 20

Page 30: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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(); } }

Java1409.java OutputJava1409.java:14: cannot resolve symbolsymbol : constructor Person09 (Person09)location: class Person09 Person09 p2 = new Person09(p1); ^1 error

Page 31: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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(); } }

Java1410.java Output

Person Class, Stage 10

Calling Default ConstructorName: SeymourYear Born: 1975Education: 18

Calling Copy ConstructorName: SeymourYear Born: 1975Education: 18

Page 32: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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; }

Java1410.java Output

Person Class, Stage 10

Calling Default ConstructorName: SeymourYear Born: 1975Education: 18

Calling Copy ConstructorName: SeymourYear Born: 1975Education: 18

Page 33: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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 anobject of the same class as the copy constructor.

Page 34: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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"); } }

Java1411.java Output

Person Class, Stage 11

MAIN, LEVEL 1showData for: p1 Name: Kathy

MAIN, LEVEL 2showData for: p2 Name: Joseph

MAIN, LEVEL 3showData for: p1 Name: KathyshowData for: p2 Name: JosephshowData for: p3 Name: Elizabeth

MAIN, LEVEL 2showData for: p1 Name: KathyshowData for: p2 Name: Joseph

MAIN, LEVEL 1showData for: p1 Name: Kathy

Press any key to continue. . .

Page 35: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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(); } }

Java1412.java Output

Java1412.java

showData for: p1 has name KathyshowData for: p2 has name TomshowData for: p2 has name KathyshowData for: p2 has name GeorgeshowData for: p1 has name George

num1: 15num2: 25num2: 15num2: 100num1: 15

Page 36: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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; }}

Java1412.java Output

Java1412.java

showData for: p1 has name KathyshowData for: p2 has name TomshowData for: p2 has name KathyshowData for: p2 has name GeorgeshowData for: p1 has name George

num1: 15num2: 25num2: 15num2: 100num1: 15

Page 37: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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"; }}

Java1413.java Output

Java1413.java

p1 value: Person@df6ccdp2 value: Person@601bb1

p2 value: Person@df6ccd

Page 38: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

What is going on? Part 1Figure 14.18 shows 2 strings and 2 integers are stored.

Page 39: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

What is going on? Part 2Figure 14.19 shows the result of making the two assignment statements:

p2 = p1;num2 = num1;

Page 40: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

Objects and Simple Data TypesStore 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.

Page 41: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

What is going on? Part 3Figure 14.20 shows the result of making the two assignment statements:

p2 = George;num2 = 100;

Page 42: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

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).

Page 43: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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; }}

Java1414.java Output

Java1414.java

p1 value: Person@df6ccdintList1 value: [I@601bb1

p2 value: Person@ba34f2intList2 value: [I@ea2dfe

Calling parameterDemo methodParameter years value: 7Parameter p value: Person@df6ccdParameter list value: [I@601bb1

Calling parameterDemo methodParameter years value: 20Parameter p value: Person@ba34f2Parameter list value: [I@ea2dfe

Page 44: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// Java1415A.java// This program demonstrates that the simple data type variable used in parameter// passing is not altered by any method process. It tries to show that the object // is altered, but since myName is an object of the String class it remains unaltered.

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();

}

Java1415A.java Output

Java1415A.java

main method valuesintNum: 100myName: Bob

qwerty method valuesnum: 200name: Joe

main method valuesintNum: 100myName: Bob

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);}

Page 45: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// Java1415B.java// This program PROPERLY demonsrates that the simple data type variable // used in parameter passing is not altered by any method process. The object is altered. public class Java1415B{

public static void main (String args[]){

System.out.println("\nJava1415a.java\n");int intNum = 100;myClass myObject = new myClass();System.out.println("main method values");System.out.println("intNum: " + intNum);System.out.println("myObject.getName(): " + myObject.getName());qwerty(intNum,myObject);System.out.println("\nmain method values");System.out.println("intNum: " + intNum);System.out.println("myObject.getName(): " + myObject.getName());System.out.println();

} public static void qwerty(int num, myClass myObject)

{ num += 100; myObject.alterName("Joe"); System.out.println("\nqwerty method values");

System.out.println("num: " + num);System.out.println("myObject.getName(): " + myObject.getName());

} }

Java1415a.java Output

Java1415a.java

main method valuesintNum: 100myName: Bob

qwerty method valuesnum: 200name: Joe

main method valuesintNum: 100myName: Joe

class myClass{ String name; myClass() { name = "Bob"; } void alterName(String newName)

{ name = newName; } String getName() { return name; }}

Page 46: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

Java ParametersJava passes information to a method with parameters.

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

Altering a simple data type parameter inside a method does not alter the value of the calling parameter.

Altering an object parameter inside a method alter the object value of the calling parameter, because objects pass the memory reference where object information is stored.

It is true that strings are objects. However, strings are a special exception. Chapter 16 will deal with exactly what is going on with Strings. For now think of Strings as simple data types.

Page 47: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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); }}

Java1416.java Output

Java1416.java

make: nullyear: 0cost: 0.0

Page 48: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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); }}

Java1417.java Output

Java1417.java

Make: ExplorerYear: 2002Cost: 30000.0

Page 49: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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; }}

Java1418.java Output

Java1418.java

Cylinders: 8Size: 4.7HorsePower: 265

Page 50: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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 slideclass 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()); }}

Java1419.java Output

Java1419.java

Engine Object FinishedCar Object FinishedcarMake: TundracarDoors: 4carColour: Redcylinders: 8size: 4.7horsePower: 265

Page 51: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

Information Hiding

Information Hiding is the concept of thinking about programming features and using programming featureswithout concern, or even knowledge, about the implementation of such features.

Page 52: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

OK, I put the key in the ignition and turn the key. This will complete an electronic circuit and activate the starter motor. As the starter motor turns the engine over, the following process brings the car in motion. Fuel is pumped from the tank to the fuel injectors. The fuel injectors convert the liquid gas to a fine spray and inject this spray inside the chambers of each cylinder. The turning of the engine moves the pistons upward inside the chambers and it compresses the gas into a tight space. With perfect timing the rotor, inside the distributor, completes an electric circuit that sends an electric pulse to the appropriate cylinder. The electric pulse is passed through a spark plug that protrudes inside the cylinder and a small spark is emitted in the chamber. The compressed gas is ignited by the spark and explodes. The explosion causes instant expansion and the piston is driven downward in the cylinder. The piston head is connected to a piston rod, which moves up and down. The up and down motion of the piston rod from the repeated explosions is converted to a circular motion. This circular motion is than transferred to the crankshaft. The crankshaft continues the energy path to the transmission. The transmission then selects the appropriate gear for the car movement. From the transmission the turning force goes by drive shaft and various universal joints to the differential. The differential distributes the turning force to the wheels and the car starts to move.

Page 53: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

Reasons for Information Hiding

There can be valid economic reasons.

Implementation details may be too complex andtoo difficult to understand

It allows focus on a new and different topic withoutconcerns about prior details.

Page 54: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// Java1420.java// This program demonstrates information hiding. A series of fishes is drawn on a two-dimensional fishtank// grid. A special FishGfx class is used without knowing any of the methods implementations.// This program needs top be viewed in 1024 X 768 resolution.import java.awt.*; public class Java1420 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,String.valueOf(count)); count++; clr++; if (clr > 9) clr = 1; f.drawFish(g,col,19-col,clr,String.valueOf(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); } }}

Java1420.java Output

On next Slide...

Page 55: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class
Page 56: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// 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

public void drawFish(Graphics g, int row, int col, int clr, String str) // draws a fish at the specified [row][col] grid location with color (clr) and a string character, which // usually is a converted integer an intentional time delay is called at the conclusion

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

Page 57: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// Java1421.java// This program demonstrates the use of static "class" // methods that do not require the creation of an object.

public class Java1421{ public static void main(String[] args) { System.out.println("\nJava1421.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 Output

Java1422.java

100 + 33 = 133.0100 - 33 = 67.0100 * 33 = 3300.0100 / 33 = 3.0303030303030303

Page 58: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// Java1422.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 Java1422{ public static void main(String[] args) { System.out.println("\nJava1422.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; }}

Java1422.java Output

Java1422.java

100 + 33 = 133.0100 - 33 = 67.0100 * 33 = 3300.0100 / 33 = 3.0303030303030303

Page 59: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

Class MethodsIt 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));

Page 60: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// Java1423.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 Java1423{ public static void main(String[] args){ System.out.println("\nJava1423.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(); }}

Java1423.java Output

Java1423.java

Starting with default high score of 1000

Tom's score is 6724 compared to 1000 high score

Sue's score is 3396 compared to 6724 high score

Lois's score is 6132 compared to 6724 high score

Highest score is 6724

Page 61: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// This class is used with program Java1423.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 Output

Java1423.java

Starting with default high score of 1000

Tom's score is 6724 compared to 1000 high score

Sue's score is 3396 compared to 6724 high score

Lois's score is 6132 compared to 6724 high score

Highest score is 6724

Page 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

// Java1424.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 Java1424{ public static void main(String[] args) { System.out.println("\nJava1424.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"); }}

Java1424.java Output

Java1424.java

Starting school balance: 100000

Constructing English object with 20000Constructing Math object with 15000Constructing Comp Science object with 6000

Deduct 5000 from English15000 left in English95000 left in school budget

Deduct 8000 from Math7000 left in Math87000 left in school budget

Deduct 9000 from Comp Science-3000 left in Comp Science78000 left in school budget

Page 63: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

// This class is used with program Java1424.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); }}

Java1424.java Output

Java1424.java

Starting school balance: 100000

Constructing English object with 20000Constructing Math object with 15000Constructing Comp Science object with 6000

Deduct 5000 from English15000 left in English95000 left in school budget

Deduct 8000 from Math7000 left in Math87000 left in school budget

Deduct 9000 from Comp Science-3000 left in Comp Science78000 left in school budget

Page 64: Important Java Reality A Java program consists of one or more class declarations. Every program statement must be placed inside a class. public class

Static Methods and Attributes

Static methods and static attributes can be accessed for the entire duration of a program.

Static attributes can be accessed by static methods and object methods.

Static attributes can be accessed with object identifiers and class identifiers.