More Object Concepts
Chapter 4

1. Understand blocks and scope
2. Overload a method
3. Avoid ambiguity
4. Use constructors with parameters
5. Use the this reference
6. Use static variables
7. Use constant fields
8. Use automatically imported, prewritten constants and methods
9. Use Gregorian Calendar
10. Understanding composition
11. Using nested and inner classes

Important Points.

1. Understanding blocks and scope.
a. The code between a pair of curly braces is called a block.
b. It is not terminated by the ;
c. A block can be nested inside of  another block.
d. The inner block is executed first.
e. A variable comes into existence when declared (in scope) and ceases to exist (goes out of scope) at the end of the block.

{   code - var a - in scope
     { code var b - in scope
          { code executed first - var c - in scope

          } variable c out of scope
     } executed second - variable b out of scope
} executed third - variable a out of scope

f. You can create as many variables and blocks as you need within any program but only if you have reason. Too many will confuse you.
g. When declaring a variable more than once in a block, you are attempting to re-declare the variable.  Error.
h. A locally declared variable always masks (overrides) other variables with the same name in another method.
i. If a local variable or parameter in a method has the same name as a class field, the field is hidden until the block terminates. This is called Shadowing.
j. Within the method, the methods local variable overrides the instance variable. A variable ceases to exist at the end of the block in which it is declared.  You cannot declare the same variable name more than once within a block, even if a block contains other blocks.

2. Overloading a method - refers to using one term to indicate diverse meanings or writing multiple methods with the same name but with different parameter list. When you overload a Java method, you write multiple methods with a shared name. The complier understands based on the arguments passed.
For example:

Public static void calculateInterest(double bal, double rate)
     double interest:

     interest=bal* rate;
     System.out.println("Simple interest on $" + bal + " at " + rate + "% rate is " + interest);

//Double rate would be entered as 0.04, whereas in the following, rate can be entered as an integer.

Public static void calculateInterest(double bal, int rate)
     double interest, rateAsPercent;
     rateAsPercent=rate/100.0  //this line converts rate into a percent using the int argument passed as rate.

     interest=bal* rateAsPercent;
     System.out.println("Simple interest on $" + bal + " at " + rate + "% rate is " + interest);

a. Both of the above methods have the same name but will have different arguments passed to it.  By overloading the calculateInterest method with two methods of the same name receiving different arguments one can accommodate two different arguments. You overload methods correctly by providing different parameter lists for method with the same name.
b. Methods with identical names have identical parameter lists, but different return types are not overloaded - they are illegal.

3. Learning about ambiguity. As we have learned, overloading a method is useful when different arguments are passed. Ambiguous situations occur when the complier cannot determine which method to use.
(int bal, double rate) the argument passes an int and double. this exists
(double bal, int rate) the argument passes a double and int. this exists
(int bal, int rate) the argument passes an int, and int and is ambiguous because there is no method for arguments(int bal, int rate)  The complier would not know which method to call.
a. If the keyword final appears in a method's parameter list, it is ignored when determining ambiguity.

void aMethod(int x)
void aMethod (final int x)   //these statements set up ambiguity as the complier sees them as the same.

4. Using Constructors with Parameters. We often use constructors to insure that fields within classes are initialized to some appropriate default value. When writing custom constructors you can write versions that receive parameters that are used to initialize data fields for an object.
a. When you write a constructor, it can be written to receive parameters or not, which often are used to initialize data fields for an object.
b. If a classes’ only constructor requires an argument, you must provide an argument for every object of the class that you create.
c. A default constructor takes no arguments.

public class Employee
     private int empNum;     //Any time an employee object is created such as partTimeWorker=new Employee() you ensure that the employee constructor that all
     Employee()              //employees with have an initial empNum of 999.  

d. A constructor assigns the values at the time of creation.

5. This reference. Refers to the current object that has the focus.
a. It is not necessary to store a separate copy of each variable and method for each instantiation of a class.
b. When you want each object to have a unique field value, you do not define the field as static.
c. In Java just one copy of each method in a class is stored and all instantiated objects can use that copy.
d. The reference to an object that is passed to any object's nonstatic method is called the this reference.
e. The this reference is always there working behind the scenes so that the data field for the correct object can be accessed.
f. Only nonstatic methods receive this reference.
g. You cannot call this() from other methods in a class; you can only call it from constructors and it must be the first statement within the constructor.

public class Student
    private int stuNum;
    private double gpa;
    Student(int num, double avg)
        Student(double avg)
        this (999, avg);          //use this here instead stuNum=999;    using the this reference from one constructor version to call another version.
    }                             //gpa=avg;
        Student(int num)
        this(num, 0.0);   //use this here instead studNum=num;
    }                             //gpa=0.0;
        this(999,0.0);          // use this here instead studNum=999;
    }                           //gpa=0.0;

h. You want each instantiation of a class to have its own nonstatic data fields, but each object does not need its own copy of most methods.
i. When you use a nonstatic method, the compiler accesses the correct objects field because you implicitly pass an object reference to the method.

6. Using static variables - methods without objects are static. Static methods do not have a this reference because they have an object associated with them and are called class methods.
a. Class variables are variables that are shared by every instantiation of a class.
b. Methods declared as static cannot access instance variables, but instance methods can access both static and instance variables.
c. Methods declared as static are called class methods.
d. Class variables are variables that are shared by every instantiation of a class.

7. Using constant fields.
private static final int SCHOOL_ID=12345;   You can use the keyword final with methods or classes. Final indicates limitations placed on inheritance.
b. Fields that are final also can be initialized in a static initialization block.
c. Fields declared to be static are not always final. Final fields are not always static.
d. A static field’s value is shared by every object of that class.
e. A final static field’s value is shared by every object of a class.

8. Using automatically imported, prewritten constants and methods.
Package or library of classes - java.lang is the class that is imported into every java program.  It contains fundamental classes as opposed to optional classes that must be explicitly named.
a. java.lang.math contains constants and methods that can be used to perform common mathematical functions and are static in the math class. Class variables and class methods.
b. The java.lang package is imported automatically into your programs so
areaOfCircle = Math.PI*radius*radius

Math Methods


Value that the method returns


absolute value of x


Arc cosine of x


Arc sine of x


arc tangent of x


Theta component of polar coordinate(r, theta) that corresponds to the Cartesian coordinate x,y


Smallest integral value not less  than x (ceiling)


Cosine of x


Exponent, where x is the  base of the natural logarithm


Largest integral value not greater than x


Natural logarithm of x


larger of x and y


smaller of x and y


x raised to the y power


Random double number between 0.0 and 1.0


closest integer to x(x is a double, and the return value is expressed as a double)


closest integer to x(where x is a float or double, and the return value is a int or long)


sine of x


Squareroot of x


Tangent of x

c. All constants and methods in the math class are class wide (static). There is no need to create an instance of the math class. The constructor for the math class is private and programs cannot access the constructor.
d. Do not use the math class unless you understand what you are doing.

9. Using GregorianCalendar Class
a. Java contains hundreds of classes of which only a few are loaded up automatically. To use other prewritten classes you must ...
    1. Use the entire path with the class name 

my Anniversary=new java.util.GregorianCalendar();

    2. Import the class                                    

import java.util.GregorianCalendar

    3. Import the package that contains the class you are using.

import java.util.*;

the * is a wild card which can be replaced by any set of characters. This will import all the classes in the util.

b. The wild card * only works with specific packages such as .util or .lang.  The * imports all classes in a package.
c. The import statement simply notifies the program that you will be using the data and method names that are part of the imported class or package.
d. Seven constructors are available for GregorianCalendar objects.
e. Specific data field values can be retrieved from a GregorianCalendar object by using a class get() method. 

int dayofYear=today.get(GregorianCalendar.DAY_OF YEAR);


Values Returned by get()


a value from 1 to 366 


a value from 1 to 31


Sunday, Monday... corresponding to value from 1 to 7.


the current year


January, .... values from 0 to 11


a value from 1 to 12. the current hour in am or pm


AM or PM which corresponds to the value from 0 to 1


a value from 0 to 23 based on a 24 hour clock


the minute in the hour value from 0 to 59


the second in the minute, value 0 to 59


the millisecond in the second, value from 0 to 9999

10. Understanding Composition - describes the relationship between classes when an object of one class is a data field in another class.
a. When you use an object as a data member of another object, you must remember to supply values for the contained object if it has no default constructor.
b. a has-a relationship exists when a class contains data members that are objects.

11. Nested and Inner classes. In Java you can create a class within another class and store them together, called nested classes.
a. The containing class is the top-level class.
b. Static member classes- have access to all static methods of the top level class
c. Nonstatic member classes - inner classes requires an instance, it has access to all data and methods of the top-level class
d. Local classes are local to a block of code
e. Anonymous classes are local classes that have no identifier.
f. Packaging the classes together makes their connection easier to understand, and the code easier to maintain.
g. You do not have to make an inner class private, but doing so keeps it members hidden from outside classes. An inner class can access its top level class fields and methods, even if they are private and an outer class can access its inner class members.
h. A nested class resides within another class.
i. Nonstatic member classes are known as inner classes.