(syllabus and calendar)

Ch. 4. Introducing Classes, Objects, and Methods

week4-2014-fall-b.zip
with OutlineForClass.java and CopyByReferenceNameDemo.java

 

Session 4

class structure

parameterized constructor

reference type versus primitive type and the new operator

form of a class

instantiate and initialize

anatomy of a class

what is a constructor?

overview and glossary

summary of members

formal parameter and runtime argument

Vehicle class and objects of type vehicle

object creation

reference variables and assignment

methods and constructors

returning from a method

return with a void method is more radical than break

returning a value

parameters for a method

object type as a parameter

constructors

parameterized constructors

garbage collection and finalize

this - a keyword that refers to the current object

preview of arrays


Quiz

Mid-course Evaluation

Review from last week.

See http://www.write-technical.com/126581/session3/session3.htm#nested%20loop


Class Structure

Here's a class that uses the default constructor, which is implicit. What are the default values of the various types?

Let's look at a class that has fields and an explicit, custom constructor:


Parameterized Constructor

reference type versus primitive type

If you want to steer a bull, you can do so with either of its horns. Both "handles" affect the same physical object.

First, let us establish that two objects can refer to the same place in memory, such that a change to data or field of one object also changes the other object.

The output is:

Now, lets see how a value that is not a field has only its immediate value, and is not attached to any object.

Here is another example, and its shows that each constructor call creates a separate memory space.

 


Whereas an int is a primitive value on the stack, an object of any class type is a reference type on the heap.

int phoneNumber = 4153678210; // a primitive
MobilePhone shoePhone86 = new MobilePhone(); // sophisticated stealth electronics

SpecialAgent agent007 = new SpecialAgent("James Bond");

A more elaborate version is in the zip, ParameterizedConstructorDemoWithComments.java:

Object-oriented programming allows the programmer to create custom data types and use sophisticated data types that have methods, such as the methods of the String class. But compare the economy of int boilingPoint = 212, which is a simple value on the Stack, to an object such as agent007, who has a wealth of data and methods (vehicles, gadgets, tricks, desires)  that make him suitable for all kinds of assignments in all kinds of places. To load James Bond into memory is major undertaking, requiring hours to read the novel or watch the film. Instead of re-loading James Bond into memory, it would be more efficient to centralize him and have multiple references to him.

Similarly, a customer of Bank of America might have many data items and behavior options. If an object such as customer1738573 can be referenced at both the Paris office and the Tokyo office, then it is easy to change that customer's bank privileges even when that customer is visiting a foreign country.

new operator for objects and stack versus heap

HelloWorld hw = new HelloWorld();

The new operator allocates a new area of memory for the newly created object to use. The constructor does initialization for the newly created object.

Stack = primitive and fast

We do not need the constructor or the new operator for primitive operations. It is faster to work with primitive types. They reside in a last-in/first-out (LIFO) data structure called the stack.

Heap = complex and slow

Objects live in a different type of memory area called the heap. The overhead for creating and managing objects might be considered similar to the overhead of creating a spreadsheet or table to track all the members of the class. We might consider each object to be a row in the spreadsheet or table.

Copy by value (primitive) versus copy by reference (object)

Java stores each primitive type in a fixed amount of memory and Java directly manipulates the values for primitives. 

However, objects and arrays do not have a standard size, and they can become large, complex, and slow to initialize.
Java economizes memory and boosts performance by manipulating these "reference types" (objects) by reference.
(Unlike C or C++, Java does not have pointers, but a variable is a named location in memory and is internally implemented by a pointer.)

Although the reference types do not have a standard size, the references to reference types do have a standard size.

Reference types differ from primitives in the way values are copied and compared.

Primitive values inhabit a fast part of memory called the stack, which is relatively simple, like a stack of plates. Objects occupy a slower but more complex part of memory called the Heap, which is more like a spreadsheet that can have any number of rows and columns.

Reference Variable Assignment

The primitive types have copy by value by object types have copy by reference (additional assignment results in two references pointing to the same place in memory)

int myInt = 14;
int yourInt = myInt; // independent copy

car myCar = new Car();
car yourCar = myCar; // no new object created

myCar and yourCar are two reference variables, two handles on the same object, like two horns on the same bull.

A string is an object of type String, which is a reference type:

Another example of how the value of a field follows the object reference.


form of a class

instantiate and initialize

To construct an instance of a class, we call a constructor. A constructor can initialize the state of the newly created object.

Anatomy of a class with constructor and method

A class can have the following types of members, and they should be presented in this order:

Some classes do not have all three kinds of members. For example,

The Employee class definition declares and assigns a value to a field, also called an instance variable because every object (or instance) of that class, will have that field. (Sometimes the term "property" is used as if it were synonymous with field, instance variable, data, or state.

Often, a class definition defines fields, constructors, and methods. The Administrator class definition includes a constructor definition that specifies a formal parameter, and the method definition is parameterless. The following example shows that a variable can be declared at the static class level, the non-static instance level, or the local level.

VARIABLE TYPE LINE NUMBER
local variable 9, 15, 16, 23
instance variable 6
class variable (static variable) 3

The output is:
I am a member of class Instructor
I get all summer off, so my vacation amount is: 56
The output of the Instructor is 5 pages because teaching takes time.
I am a member of class Administrator
My vacation amount is: 14
I issue policy statements.
The administrator writes 120 pages. and has the title of Administrator


The following program demonstrates the use of:
1. fields
2. constructors
3. methods
4. and that a method can have a formal parameter that is an object rather than a primitive.

The following example demonstrates the use a static or class-level field, as well as the use of the keyword "this" to differentiate between a field on this object and the formal parameter of the same name.

The following example calls the implicit constructor.

Here, we use a custom constructor and also call a method that returns a double.

What is a constructor call?

A constructor is different from a method, although it easy to confuse the two.

A constructor implicitly returns a newly created object with its members in a valid state. Perhaps it is helpful to make an analogy with DNA. We are born with DNA that provides us with a valid initial state, such as having 10 fingers and 2 eyes.

Similarly, we can say that a scientist or an inventor is a class of person with certain abilities. How these abilities work out depend upon the particular environment, such as time and place of birth.

 

The output is:

I am a scientist object, and my unique ID in the JVM is: 1211154977
I am a scientist object, and my unique ID in the JVM is: 2031692173
This is 1211154977 and I use two lenses to look up at stars the sky.
This is 2031692173 and I use two lenses to look down at bacteria
swimming in water.

Note that the runtime call to the constructor on line 35 depends upon the definition of the constructor on line 10. Typically, we use the main method to make runtime calls that depend on different classes that define constructors and methods. This way, the main method runs the show, and the other classes can encapsulate the logic appropriate for such classes.

The constructor INITIALIZES the newly created object, which is an instance of a class. The class is like DNA, or like a blueprint, recipe, that is, the design rather than the embodiment.

Wall myFrontYardWall = new Wall(enoughBricks, enoughMortar, enoughLaborFromBob);

For me to get a newly created object, myFrontYardWall, which is a type of Wall, I need to call the constructor. In this case, I call a constructor that requires certain input to give me the INITIALIZED output I want. The output I want is myFrontYardWall and the input I need to give is:

Bob, the mason object, to go about  his business or craft, also needs to call a constructor.

Mortar bobMortar = new BobMortar(getSand(), getCement(), getWater());

To get sand, we need silicon dioxide, SiO2, so the creation of sand might look like this:

Sand myBeachSand = new Sand(erodeRock(), getOnePartSilicon(), getTwoPartsOxygen());

In other cases, we do not have such a detailed constructor, and for our convenience Java gives us a "default constructor".

Light light = new Light();

Summary: The syntax for object instantiation is typically:

type identifier = new constructor(arg1, arg2);

where:

Let's try it for orange juice.

OrangeJuice myOJ = new OrangeJuice(myBigOrange.squeeze());

Summary: Although a constructor looks similar to a method, a constructor does NOT have a return type. The compiler does not allow you to specify a return type for a constructor. The purpose of the constructor is to perform initialization when a object is created. Whereas a method name should be a verb, and constructor name MUST be exactly the same as the class name.

A constructor definition "precedes" a constructor call. Now let's look at working code that has a class that DEFINES a constructor, and another class that CALLS the predefined constructor.

The class with main does the object initiation by calling a constructor that is defined in a different class.

Overview and glossary

A procedural programming language, such as C, has its own advantages (such as performance) and disadvantages (non-portability, need for careful memory management). Java does not perform as fast as native C. However, Java does have the advantages of object-oriented programming over procedural programming for code reuse and customization (including the custom data types known as classes): encapsulation, inheritance, and polymorphism.

An object is an instance of a class. A class is a template for instantiating (and initializing) objects. A class can have fields, constructors, and methods.

HelloWorld.java is mostly procedural. We did not instantiate an object of type HelloWorld:

    HelloWorld hw = new HelloWorld();

The only method we used was println(), which is on the static output stream, out

and out is a static field of System, which is part of the java.lang package

    http://java.sun.com/javase/6/docs/api/java/lang/System.html

which is automatically available to every program. This means that HelloWorld does not reveal all the typical tasks of writing an object-oriented program.

For example, if we want to use a non-static method, we must first instantiate an object of the class that defines the method we want to call. It is not necessary to assign a name (or identifier) to the newly created object.

The two phases involving a method are:

  1. method definition
  2. method invocation

The necessity of two phases is already familiar to us from our work with variables:

  1. declare and assign a value to a variable
  2. use the variable

What is new is that whereas a variable can be declared and assigned a value is a single statement, a method definition requires considerably more, including a code block.


Object-Oriented Glossary

class

The class defines the behavior and attributes of the object. An object is an instance of a class. A class is a template that defines the form of an object.

When I visit a retail store, each employee might have a unique name tag and be a unique "object", but I expect them to follow the role of RetailEmployee, that is, to be instances of the class RetailEmployee.

In the real world, we deal with objects. Who has eaten Food today? No one. But we all ate some food objects. Each McHeartAttack's french fry is an object of type FrenchFry that fits the template and has attributes of length, width, color, and temperature.

A class is, in effect, a custom data type. Even the primitive data types, such as int, can be represented by a corresponding class, such as Integer. When you create classes for your applications, you create your own custom data types. Much of the value of object-oriented programming is the ability to create the custom data types or classes that serve your business needs or scientific research, that is to say, that fit the problem domain.Object-oriented programing allows to create and reuse domain-specific logic. Procedural programming has no concept of a specialized domain.

class members

The Java API Reference provides information about the members of the classes that belong to Java Development Kit:

Summary: The members of a class are fields, constructors, and methods. Their declarations or definitions should appear in this order.

Using the dot (.) operator, you can access a field or a method on an object. For example,

main()

The main() method is the point of entry for execution. Your application must have a main method in a file named for the class that contains the main method. Your application can have other classes, and they do not have a main method. (An applet does not have a main method because the Java virtual machine is already available for executing byte code within a web browser.)

dot operator

The dot operator enables you to access a class member through an instance of the class. I get the value of Food by accessing concrete objects that exist in memory, such as  myFrenchFry.calories or myFrenchFry.flavor.
Use this syntax with the dot (.) operator:

object.member

Note: In the case of System.out.println() the syntax is:

class.static_field.method


Encapsulation

The class is a unit for encapsulation.

A class has methods (behavior) and fields (attributes). 

In Java, the unit of encapsulation is the class. Each object is an instance of a class. The class is a template for making objects. The class is similar to a recipe, rule book, set of laws, cookie cutter, or a mold, for making things of a certain shape, things with certain attributes. If I define a class called Dog, it might have the behavior of bark() and wagTail(), and an attribute for number of legs, which might be set to four:

int numberOfLegs = 4; // this attribute could be private or public - if hidden, it's more encapsulated

A string is implemented inside Java as an object of the class String. A string object has the length method.

    http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#length%28%29

Note that an array has the length field instead of a length method. For example,
the number of elements in the array of command-line arguments for main:

    public static void main(String[] args)

can be accessed as args.length
 
Summary: an array has the length property to store the number of items in its collection, but other objects have the length() method, such as myString.length(), which stores the number of characters in the String.

This example shows using that length() method on a string object with the identifier (or name) s.

I don't need to know how the length method works. The details are encapsulated in the class that defines the method. Encapsulation has the benefit that the vendor or software provider (Sun or Oracle) can improve the performance of the method (or fix its bugs) without breaking my code that uses this method. In other words, encapsulation protects the consumers of the API.

Similarly, if you know how to drive an automobile with the encapsulated acceleratorPedal, the manufacturer can improve the engine (implementing an electric engine, or solar engine, in place of a petro-chemical engine), and your method of pedalToTheMetal() still works. Unfortunately, the term "gas pedal" has a non-encapsulated implementation attached to it: it assumes a gasoline-powered engine. Does the big-rig truck driver refer to the diesel pedal? It would be poor design to designate either a batteryPedal or gasPedal. The attribute is acceleration. Therefore, in an all-electric vehicle, we refer to the accelerator pedal, not the gas pedal.

Inheritance

Inheritence is a hierarchical concept.

ConstitutionalFramework
    FederalLaw
        StateLaw
            CountyOrdinance
                CityOrdinance
                    DepartmentRules

The subclass is a unit for inheritance (from its superclass).

Polymorphism

The method is a unit for polymorphism. Overloaded constructors are another polymorphic aspect. Most of the code might be reusable between two signatures of the same method if they both call the same constructor or method.

Here, two signatures of a method are defined so that runtime calls can choose between to two signatures which happen to have different but related implementations:

Here, two signatures are used to define an overloaded constructor:


Example of a Class: Help

What datatype does the isValid boolean method of line 57 require? 

Why does the return value of the read method undergo a cast in line 73?

Where does the myHelpObject object get the showMenu method?

Which method is being called in line 73? Is that method name overloaded with multiple signatures? Is this an example of polymorphism?

http://java.sun.com/j2se/1.4.1/docs/api/java/io/InputStream.html#read()


Overview of OOP

So we know that an array can store many values of one, and only one, type.
What if we want a way to associate values of different types?
An object is not an array, and not even a multi-type array, but an object does allow us to get and set a multiple types (and an array can contain objects).
An object is surely less primitive than a "primitive", and perhaps closer to real-world objects insofar as it can be more complex.
An object is a custom data-type that can have both data and behavior.

A tutorial on object-oriented programming concepts: http://docs.oracle.com/javase/tutorial/java/concepts/index.html

Procedural languages, such as C, center around code, and what the code does. To write procedurally, you have to think like a computer.

Object-oriented languages, such as Java, center around objects, which can be specific to the problem domain that concerns you, and which is more like how human beings understand the world. For example, you can model your program on how you model your business, with "real world" objects such as

Objects are at a higher level than routines. Objects involve the abstraction of details. You design an object-oriented system by thinking about self-enclosed, discrete entities (objects) that send messages to each other. This is analogous to how a real-world customer sends an order to a vendor.

Some Java applications serve a business workflow based on a business model of business objects. Corresponding to each business object (Customer, Salesperson, Order) can be a database table, which in  term corresponds to a Java object that contains the business logic for that business object. In such a scenario, a database field (table column), such as Name or ZipCode can correspond to an object attribute or property. In this sense, the term field can have a common meaning in database design and programming.

Many software companies use Java to write middleware that sits between the end-user and the relational database. The middleware has business rules, and sometimes has classes that map closely with database tables. However, object-oriented programming and relational databases are not exactly the same, and there are challenges in getting them to work well together. This is sometimes called the impedance mismatch. See http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch

Object-oriented programming with its classes provides a layer of abstraction that is analogous to the real world, but also distant from the native operating system code. This helps us understand why object-oriented programming is not as fast a programming with primitive types: a class can have more complexity than a spreadsheet, and as much complexity as a large database table.

The three key concepts of object-oriented programming are:

Encapsulation

Encapsulation is like a capsule: the doctor tells you to take a medicinal capsule or pill. Far too small for you to see is the structure of the compound or molecule that does work in your bloodstream or organs to cure your disease. You don't even see the components of the mixture, which might be gray bitter-tasting medicine mixed with white sugar and blue flour. The complexity is hidden from you. Your orders are simple and external to the encapsulation: take one blue pill each day with water.

Encapsulation is like a black box. When you purchase a television set, you do not need to know the details of the electronics inside

Instead, you only need to know how to plug in the UNIT, attach the cable, turn the on switch, and press buttons on the remote control. You have a UNIT that sends visual and audio messages to you, and you do not care about the hidden actions within the unit.

In Quality Assurance, the phrase "black box testing" means observing the behavior of the unit from outside, without having access to the internal source code.

Similarly, cccording to Behaviorism, a school of psychology, even if we say we "know" a person, we do not know the details that are internal to that person, only the messages that the self-encapsulated "person unit" makes accessible or public in some way, such as through words or deeds.

Even within the electronics (or electro-chemtronics) of our own nervous system, an encapsulated program regulates our heartbeat (and while sleeping, our breathing) without our conscious control. The messaging between brain and cardiac muscle is hidden from us. The same is true with the coordination of muscles involved in sneezing, speaking,  swallowing, digesting food, walking, contracting and dilating the pupils to adjust to ambient light, and 99.9% of what we do. This encapsulation is essential to avoid information overload from background processes so we can focus on conscious decisions, such as whether to use a for loop or a do while loop.

A class has methods and attributes 

In Java, the unit of encapsulation is the class. Each object is an instance of a class. The class is a template for making objects. The class is similar to a cookie cutter, or a mold, or a blueprint, for making things of a certain shape, things with certain attributes. If I define a class called dog, it might have an attribute for number of legs, which might be set to four:

int numberOfLegs = 4; 

(When I go to the pet store to buy a dog, I do not purchase the class of Dog. Rather, I purchase an instance (an embodiment) of the class Dog.
I purchase Fido, Rover, Lassie or another actual dog to whom I might have not yet have assigned a name.)

Back to the class of Dog (that is, to dogs in general).
Unless I only want a statue of a dog, I want the dog to be able to do things.

 

static is like taxidermy

There is kind of static statue making called taxidermy, but only the dynamic state independent on static taxidermy can make use of behavior (methods).

The dog class might have an action (or behavior, or method) for:

These distinguish the class Dog from the class Cat that has:

 

Encapsulation supports re-use of code

Encapsulation: I do not care about the bio-electro-chemistry that makes the tail muscles contract and produce tail wagging. I just want to see my dog happy, tail a-wagging.
I do not care about the intricate machinery in the dog's nose that enables the dog's identifyAnythingWithinTwoSecondsBySent() method. I just want my dog to recognize me at night, even in darkness, without barking at me or biting me.

if (myDog.identifyAnythingWithinTwoSecondsBySent("stranger")
{
   bark();
   bite();
}
if (myDog.identifyAnythingWithinTwoSecondsBySent("owner" || "strangerOfferingMeat")
{
   wagTail();
}

Encapsulation simplifies things for whatever communicates with the encapsulated object. The internals can change without affecting the overall behavior. For example, the interface to a piano is a set of piano keys and three pedals. Behind the scenes, inside the black box of the piano, are sophisticated mechanical hammers, springs, and strings. If you can play a cheap, honky-tonk, out-of-tune piano, you can also play the world's most expensive Steinway concert piano, and without having to understand Steinway's patented hammer action. Indeed, I can then also play an electric piano (or even pick out a tune on a vibraphone, xylophone, or glockenspiel), which might be a unit that encapsulates different methods for making sound, yet offer me the same user interface of a set of PianoKey or PianoKey-Like objects.

Where is the messaging in this piano metaphor?

  1. The pianoKey object,
  2. upon the event of being pressed,
         event = pianoKey.keyPressed(middleCKey);
  3. sends a message to the hammer object,
         message = pianoKey.prepareToHitString(middleCString);
  4. which in turn sends a message to the pianoString object
         message = hammer.bangOnString(middleCString);
  5. and the pianoString object sends a message to the pianoPlayer object
         sound = middleCString.Ouch();

Indeed, I can re-use my code that tracks a particular arrangement, such as the notes of scale, no matter which keyboard instrument I play. I might even be able to transfer knowledge of the piano scale to the guitar fretboard.

Piano major scale with 3-4 and 7-1 being half-steps:

Guitar fretboard major scale with 3-4 and 7-1 being half-steps:

Inheritance

Inheritance enacts the reuse of code. For example, now that I have a messaging system for the middle C key, I can reuse that logic for all 88 keys on the piano. Each key can inherit attributes (properties) and behavior (methods) from the PianoString class, the template or mold for all strings.

When you design a more complicated system, your class hierarchy will have more levels. For example, if you were designing a library catalog, you might layers such as these:

Business rules are enforced by inheritance:

Therefore, whatever object is a member of the JapaneseMonthlyPeriodical class, will automatically inherit the logic common to LoanObject, that is, the ability to be "checked out". I do not have to rewrite the logic for the procedure of checking out a JapaneseMonthlyPeriodical and make it different from the procedure for checking out a EuropeanLanguageMonthlyPeriodical. It is like inheriting money or kingship: I do not have to do work to get the money or the crown.

Inheritance as Specialization

However, it might WANT to over-ride what an object inherits. For example, I might want the

In other words, I might want to have different styles or forms of checkout rules. The ability to have many (poly) forms (morphs) is called polymorphism.

Suppose you have a class hierarchy involving three classes, Circle, Square, and Rectangle, which all inherit the calculateArea() method from the Shape class (or, as we shall see later, interface). Polymorphism enforces that each class implementation has a calculateArea() method, but allows each implementation class redefine the inherited or required method to fit the shape. For example,

class Circle implements Shape  {
   public double calculateArea()   {
      circleArea = pi * radius * radius;
      return circleArea;
   }
}

class Triangle implements Shape  {
   public double calculateArea()   {
      triangleArea = base * (height/2);
      return triangleArea;
   }
}

Polymorphism

Polymorphism means "many forms". A behavior or method can have more than one form.

eatFood(wooden chopsticks); // typical of China
eatFood(metal chopsticks); // typical of Korea
eatFood(fork, knife); // typical of French nobility
eatFood(rightHand); // typical of Morocco
eatFood(rightHand, leftHand); // typical of baseball stadium hotdog devotees
eatFood(intravenous tube); // typical if digestive system does not function

A case of polymorphism could be in banking. Suppose that my bank allows me to open two kinds of accounts: a standard account that only requires a minimum balance of one cent (but charges service fees), or a deluxe account requires a minimum of one thousand dollars (and provides services without fee). Therefore, the openAccount() method has two forms or two signatures.

if (deposit => standardMinimum | deposit <=deluxeMinimum)
{
     StandardAccount.openAccount();
}
else
{
     DeluxeAccount.openAccount();
}


Let's Discuss OOP and do some review

  1. Name the three concepts (or buzzwords) in object-oriented programming?
  2. A Java class is the unit of which major feature of object-oriented programming?
  3. True or False: A class is an instance of an object?
  4. What are the "reserved words" in the HelloWorld program?
  5. Which aspect of OOP is hierarchical?
  6. Which aspect of OOP specializes a method so that it can have varied signatures?
  7. Which aspect of OOP "hides" data and behavior?
  8. Match the word with the correct definition:

    (1) block
    (2) parse
    (3) compile
    (4) comment

    (a) to process the syntax of tokens in source code
    (b) to convert source code to byte code
    (c) the section of code to treat as a single statement, even if it has multiple lines
    (d) the part of the source code that does not become byte code

Object-Oriented Programming -- with more examples

Class: its form and examples

INTRODUCTION: A class is the basic form of encapsulating the logic of an object-oriented program. The compilation unit assumes the existence of a class. The compiler outputs a class file. Let's look at what is a class by looking at the example of a box.

Just as integer (int) and boolean are data types, so each object is an instance of a particular class.
The class to which an object belongs is its type.
When you define a class, you are essentially creating a custom data type.
(In this sense, object-oriented programming allows you to extend the programming language!)

Each an every object is an instance of a class. A class is a template for creating objects.

The Unified Modeling Language (UML) is an industry-standard set of conventions for designing and analyzing classes.
Note in the diagram below the convention of putting the class name at the top, followed by a section for properties (nouns), and at the bottom a section for methods (verbs).

http://www.agilemodeling.com/style/classDiagram.htm


Synonyms:

Summary:

Note that the length() method is poorly named. It should be named getLength() because it returns a value. Alternatively, it should be a property rather than a method, which is the case for arrays. For example, args.length.

Exercise of naming fields and methods

Let's practice object-oriented modeling of fields and methods:

A Student has ___[noun/field]__________ and does _____[verb/method]_________.

A Customer has ___[noun/field]__________ and does _____[verb/method]_________.

An Employee has ___[noun/field]__________ and does _____[verb/method]_________.

A Car has ___[noun/field]__________ and does _____[verb/method]_________.

A Microwave Oven has ___[noun/field]__________ and does _____[verb/method]_________.

A hand-held calculator has ___[noun/field]__________ and does _____[verb/method]_________.

A Calculate module within the calculator's software has _____[verb/method]_________. (A class does not necessarily have a field.)

A Recipe has ___[noun/field]__________. (A class does not necessarily have a method.)

A Book has ___[noun/field]__________. (A class does not necessarily have a method.)


(If you are interested in UML, see http://www.rational.com/uml/leaders/index.jsp)

What does the following code snippet do?

class Box {
   double width;
   double height;
   double depth;
}

In the class declaration, we create no object! There is only logic, no embodiment, no instance.

Because Java is a strongly-typed language, we need to declare the data type of each instance variable in a class.
And, each instance (each object) of the class has its own copy of the classes instance variables.
Think of it this way: if I have a blueprint for a house with three bedrooms and two bathrooms, each house I build with the blueprint will have three bedrooms and two bathrooms.

Declaring Objects

Box myBox; // declares an instance variable that holds the value null
mybox = new Box(); // calls the constructor and allocates memory to a new object (instance)
                   // that inherits the properties and methods of the class template

Note: The primitive data types, such as int, do not require the new operator because they are not objects. Indeed, they store their value directly.
However, a string is an object, yet you have declared String myString without having to use the new operator.
This is a convenience to you.

Just as primitive variables can be declared, and later assigned values, so object types can be declared, and later instantiated.

Assign Object Reference Variables

We saw already that two String objects are two separate objects, even if they hold the same value.

Comparing objects

This like saying:

Box b1 = new Box():
Box b2 = new Box();

On the other hand, if we say

Box b1 = new Box();
b2 = b1;

then b2 refers to the same single box object that b1 does.
Because there are two references to one object, either "handle" can modify the object they both point to.
What happens if we now say this:

Circle b2 = new Circle();

Do b2 and b1 still point to the same object, or has the most recent assignment pointed the two instance variables to different objects?
Do b2 and b2 still refer to objects of the same type or class?

Let's examine this example.

The output is:

Volume is 3000.0
Volume is 162.0

What happens in line 12? Line 13? How does mybox1 get a width variable?

Vocabulary: formal parameter versus runtime argument

Summary: Within a method definition, you specify any formal parameters. When you call the method, you pass in runtime arguments that match the data type of the formal parameters. What is formal about formal parameters is that you specify the data type or custom type. When the method call includes a runtime argument, the compiler will attempt to verify that the argument is of the required type.

Let's examine the formal parameters to the method that sets the dimensions of the box as runtime arguments.

The output is:

The volume of myBox1 is 6.0
The volume of myBox2 is 13.125
The width is myBox1 is 1.0 and the width of myBox2 is 1.5

Note: formal parameters involve declarations of type while runtime arguments involve concrete assignments.


Example of a Vehicle

Different instances of the same class can have different data. To create a second instance of the same class, you must re-use the new operator.


object creation

The new operator dynamically allocates memory for the newly-created object. Objects are created in memory at run-time not compile-time.

First we instantiate the class, then we use the dot operator to reference fields and call methods on that object.



methods, return values, parameters

Methods are often used to get and set the value of properties.

It is logical that the getRange() method be encapsulated within the Vehicle class rather than located in the main of the driver class. The class with main should drive the application and let each of the other classes take care of their own logical business. The getRange() method has a return type of void because it does not return any object or primitive data type. Instead, it makes a call to a method: println().

We can rewrite this method to have a return type of integer.

return keyword

Summary: The flow of execution returns to the caller of a method when all the lines of the method have been executed or the return keyword is encountered.
If a  method returns a value, the keyword return is necessary.
The Java compiler enforces your intention to get a value from the method you declare.

Return with a void method

Summary: The return keyword can also be used with a void method. A common use case is to break out of an inner loop under a specified condition. If the method is void, no return value is delivered to the calling method, but the caller is still the location to which control returns to continue the process of execution. The difference between breakand return is that breakand exits the current code block (which might be only the most nested loop) but return exits the entire method, no matter how nested.


static methods

We have used some static fields and methods, such as out field and main method.

System.out.println() involves a static field name out, which represents the standard output device, the display monitor.  http://docs.oracle.com/javase/7/docs/api/java/io/FilterOutputStream.html#field_summary

public static void main(String[] args) allows the main method to begin execution even though we do not first instantiate an object.

Summary: a static method does not require an instance of its object type. The follow example illustrates that a static method can be called without first creating an object. The advantage is that a static class is centralized and already ready for use, so it consumes less memory and does not adversely affect performance. In the normal, non-static world, the JVM has to allocate considerable resources to create an object and keep each object distinct from other objects.

The disadvantage of a static method is that it does not know about any object.



adding parameters to a method

A method can be defined to take zero, one, or many formal parameters (line 3).
At runtime, the arguments passed to the method (lines 13, 15, 17) must match the formal parameter definition.

Here, a method is defined with two parameters.

Let's apply the concept of the parameterized method to the Vehicle class.

Object parameter to a method or a constructor

Summary: The formal parameter for a method or a constructor can be:

The compiler enforces the rule that the type of the runtime argument (such as line 43) matches the formal parameter (in this case, line 26).


Review and with long example


constructors

The constructor is for initialization at object-creation time. It looks like a method but it has no return type and it must have the same name and case (capitalization) as the class for which it is used to initialized objects. The default constructor takes no runtime argument is available automatically.

However, if you define a constructor, the default constructor is no longer available. You can, however, define a custom constructor that has no formal parameter.


parameterized constructors

Although a constructor is NOT a method, constructors and methods are two kinds of class members that can be defined with formal parameters and that can take arguments at runtime.

Let's apply the concept of a parameterized constructor to the Vehicle class.


garbage collection and finalize

Demonstrate the periodic process of the JVM freeing memory if an object no longer has a reference to it. It would not be efficient to clean up memory constantly. The JVM might wait until ten thousand or twenty thousand objects are ready for clean up. A use case for the finalize() method is to close a file or database connection so that object destruction is clean.

The JVM decides when to finalize, so the timing is not under our control:

garbage collected when generator method called 573623 times
garbage collected when generator method called 573622 times
garbage collected when generator method called 626 times
garbage collected when generator method called 7835 times
garbage collected when generator method called 10338 times

There is lag time between when finalize is called and when it finishes. Here, even after the for loop is done, two more garbage collection operations need to complete:

for loop 149996
for loop 149997
for loop 149998
for loop 149999
garbage collected when generator method called 102680 times
Generator called 150000 times in for loop
garbage collected when generator method called 102679 times
garbage collected when generator method called 102678 times


this keyword is a reference to the current object

Typically, within an object's method body you can refer directly to the object's member variables.
However, sometimes you need to specify the member variable name if one of the arguments to the method has the same name.

For example, the following constructor for the HSBColor class initializes some of an object's member variables according to the arguments passed to the constructor.
Each argument to the constructor has the same name as the object's member variable whose initial value the argument contains.

class HSBColor {
    int hue, saturation, brightness;
    HSBColor (int hue, int saturation, int brightness) { // arguments
        this.hue = hue;  // this.hue refers to the member variable
        this.saturation = saturation;
        this.brightness = brightness;
    }

You must use the this keyword in this constructor because you have to distinguish the argument hue from the member variable hue (and so on with the other arguments). Writing hue = hue; makes no sense. Argument names take precedence and hide member variables with the same name. So to refer to the member variable you must do so through the current object--using the this keyword to refer to the current object--explicitly (and using the dot operator).

Some programmers prefer to always use the this keyword when referring to a member variable of the object whose method the reference appears. In their view, this makes the intent of the code explicit and reduces errors based on name sharing.

You can also use the this keyword to call one of the current object's methods. Again this is only necessary if there is some ambiguity in the method name and is often used to make the intent of the code clearer.

The keyword this is used implicitly by Java to refer to the current object.

Here, we use this explicitly to distinguish between a class property and a local variable

Preview of Arrays (a topic for next week)

An array is an object that contains either a set of primitive values or a set of objects, such as strings. Because an array is a container rather than a standard object, an array does not require a call to a constructor the way that an ordinary object would. 

 


Quiz: Session 4

  1. A class contains three kinds of members, are they should be presented in the following order:

    1. _____________

    2. _____________

    3. _____________
       

  2. Why does java.util.Date only contain two kinds of members?

  3. An object is a _r____________ type in the sense that two objects can point to the same place in __m________________, such that a change to the data of one also changes the other.

  4. The new operator allocates memory for a newly created __________.

  5. A class defines members to hold data and enact behavior. Another name for a f_____, or i__________ variable, is attribute, state, or property.

  6.  The Java term for the code that defines the "behavior" or "operation" that is callable on an object is "method" (not function), and the method name should not be a noun but rather a ___________.

  7. A constructor's name must match that of the ___________ for which it performs instantiation and initialization.

  8. True or False: An instance variable is stored in memory at the class level and a static variable is stored in memory at the object level.

  9. True or False: To use a static method, you must first call the static constructor of that class to instantiate and initialize the object.

  10. By convention, a method name begins with a letter that is ______. (uppercase or lowercase)

  11. By convention, a constructor name begins with a letter that is _______. (uppercase or lowercase)

  12. By convention, a field  name begins with a letter that is _______. (uppercase or lowercase)

  13. By convention, a constant name contains solely _________ letters and can have underscore (_).

  14. What does the keyword return do to the execution of a method that is void?

  15. What does the keyword return do if the method is not void?

  16. True or False: Like a void method, a constructor must specify a return value of void.

  17. If a formal parameter is specified in a method definition, a call to that method must include a runtime _a____________ of a matching data type.

  18. To call a method on an object (or of a class), or to access the instance variables on an object (or static variables of a class), use the _____ operator between the name of the object (or class) and the name of the method.

  19. True or False: The formal parameter in a method definition must be a primitive type, such as int, double, or boolean.

  20. A string has the length() method to represent its number of characters. An array has the ________ field to represent its number of elements, whether populated or not.

  21. A static field is also called a __c_________ variable, and a non-static field is also called an __i________ variable

  22. Fill in the blanks with appropriate names for fields (nouns) and methods (verbs).

  1. A TrafficLight has ___[noun/field - one single field]__________ and does _____[verb/method]_________ [one single method].

    A Student has ___[noun/field]__________ and does _____[verb/method]_________.

  2. A Customer has ___[noun/field]__________ and does _____[verb/method]_________.

  3. An Employee has ___[noun/field]__________ and does _____[verb/method]_________.

  4. A Car has ___[noun/field]__________ and does _____[verb/method]_________.

  5. A Book has an ___[noun/field]__________. (A class does not necessarily have to define method.)

 


In-Class Exercise

Use the following class as a template to experiment with making your own classes.
One possibility: Shape, and then “class Circle extends Shape” to calculate area and perimeter.

// This program uses a parameterized method.

class Box {
   double width; // declare
   double height;
   double depth;

   // compute and return volume
   double volume() { // declare a method
   return width * height * depth;
   }

   // sets dimensions of box
   void setDim(double w, double h, double d) { // defining
   width = w;
   height = h;
   depth = d;
   }
}

class BoxDemoParam {
   public static void main(String args[]) {
   Box mybox1 = new Box(); // create a box object
   Box mybox2 = new Box(); // create another box object
   double vol;

   // initialize each box
   mybox1.setDim(10, 20, 15);
   mybox2.setDim(3, 6, 9);

   // get volume of first box
   vol = mybox1.volume();
   System.out.println("Volume is " + vol);

   // get volume of second box
   vol = mybox2.volume();
   System.out.println("Volume is " + vol);
   }
}