Week 6—10/04/11) More object concepts Ch 7--Sharp Ch 4-

Download Report

Transcript Week 6—10/04/11) More object concepts Ch 7--Sharp Ch 4-

More Object Concepts—
Farrell, Chapter 4
Dr. Burns
Outline










Blocks and Scope
Overload a Method
Ambiguity
Send arguments to constructors
Overload constructors
This
Static variables
Constants
Automatically imported, prewritten constants and
methods
Explicitly imported prewritten class
Blocks and Scope
Public static void methodWithNestedBlocks()
{
int aNumber = 10; // aNumber comes into existence
Ssytem.out.println(“In outer block, ANumber is “ + aNumber);
{
int anotherNumber = 512;
// anotherNumber comes into existence
system.out.println(“In inner block, aNumber is “ +
aNumber + “ and another number is “ +
anotherNumber);
}
// anotherNumber ceases to exist
System.out.println(“In outer block, aNumber is “ + aNumber);
} // aNumber ceases to exist
Blocks and Scope
Blocks must be completely nested within other
blocks
A local variable declared within an outer block
remains in scope anywhere within that block
A local variable declared within an inner block
falls out of scope when control passes from that
block and the variable ceases to exist
Still more blocks and scope
Do not attempt to re-declare a local variable within
an inner block, because that variable is still
active
You cannot declare a variable more than once in a
block
You can use the same variable name within two
blocks that are not nested—they occupy
different locations in memory
Local variables….

Always mask or hide other variables in a
class that have the same name
Question
An instance of a class gets created at the
point where the keyword new appears
 Where does the instance get destroyed?
 If you exit a method that creates an object
and later return to that method, will that
instance still be there?

Overload a Method

Overloading a method means using the
same method name but with different args
and different definitions/declarations as
well

When you overload a Java method, you
write multiple methods with the same
name
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);
}
Ambiguity
When an application contains just one
version of a method, you can call the
method using a parameter of the correct
data type, on one that can be promoted to
the correct data type.
 For example, assume a method has a
single argument that has been declared to
be double. If, instead, an int is passed to
the method, the int is cast as (promoted
to) a double and there is no compiler error.

More Ambiguity
If a second method exists that will accept
an int parameter, the compiler will use the
second method rather than casting the int
to a double and using the first method.
 This is called overloading of methods or
method overloading

More Ambiguity

Consider two methods with two
arguments. In the first method the
arguments are int and double; in the
second method the arguments are double
and int If you call this method with two int
parameters, an ambiguous situation arises
because there is not exact match for the
method call.
More ambiguity
The compiler could promote the second int
to a double and call the first method or
promote the first int to a double and call
the second method
 This will not run problem-free

Send arguments to constructors

Recall that Java automatically provides a
constructor method when you crease a
class. You can, however, provide your
own constructor method if you’d like to
initialize your fields to something other
than the default initializations.
When you write your own
constructor…
You can provide for arguments or
parameters that are often used to pass
initialization values
 Suppose that full-time employees have a
field called empNum that is initialized to
999, but part-time employees have an
empNum that is initialized to 888

Example
Public class Employee
{
Private int empNum;
Employee(int num)
{
empNum = num;
}
}
Employee fullTimeWorker = new Employee(999)
Employee partTimeWorker = new Employee(888)
Overload constructors
This is just several different constructors
with different arguments types in each
 Analogous to overload methods
 Two use this capability, you have to
explicitly define at least how many
constructors?

One constructor with args, a
second with none
public class Employee
{
private int empNum;
Employee(int num)
{
empNum = num;
}
Employee()
{
empNum = 999;
}
}
this
When you create 200 instantiations of a
class, you get 200 instantiations of the
data fields (variables) in the class
 Do you get 200 instantiations of the
methods in the class???


Only the class itself maintains the methods
More of this

Suppose you need the empNum of employee
worker--the code is
Int employeeNumber = aWorker.getempNum();
This uses the employee class getempNum() method
and it gets the employee number from the instance
aWorker
The compiler figures out whose employee number is to
retrieved by the single method getempNum()
Still more of this
You implicitly passed a reference
(address) to the employee getempNum()
method by use of the aWorker
 The method actually implements code that
looks as follows:

The getEmpNum() Code
Public int getEmpNum()
{
return this.empNum;
}
However, usually you don’t have to explicitly
use the this keyword
So the code can look like
Public int getEmpNum()
{
return empNum;
}
public class Student
{
private int stuNum;
private double gpa;
Public Student(int stuNum, double gpa)
{
stuNum = stuNum;
gpa = gpa;
}
Public void showStudent()
{
System.out.printlin(“Student #” + stuNum + “ gpa is “ + gpa);
}
}
Public class TestStudent
{
public static void main(String[] args)
{
Student a PsychMajor = new Student(111,3.5);
aPsychMajor.showStudent();
}
}
The result here is…
Student #0 gpa is 0.0
 Not what we wanted…
 The compiler treats

stuNum = stuNum;
gpa = gpa;
As local variable = local variable
public class Student
{
private int stuNum;
private double gpa;
Public Student(int stuNum, double gpa)
{
this.stuNum = stuNum;
this.gpa = gpa;
}
Public void showStudent()
{
System.out.println(“Student #” + stuNum + “ gpa is “ + gpa);
}
}
The result here is…

Student #111 gpa is 3.5
Here, the use of this must be explicit,
because the use of this causes the
compiler to understand
class variable = local variable
Which is what we want
static variables are class variables
Class methods have no objects associated
with them and cannot use a this reference;
they are declared static
 Class methods, such as main are static,
they can not be used in conjunction with
instance objects
 Conversely, we should not declare
methods of classes that will be instantiated
as static

class variables
Are shared, common to every instance of
a class
 Instance variables are separate for every
instance of a class

Public class BaseballPlayer
{
private static int count = 0;
private int number;
private double batttingAverage;
public BaseballPlayer(ind id, double avg)
{
number = id;
battingAverage = avg;
count = count + 1;
}
Public void showPlayer()
{
System.out.println(“Player #” + number + “ batting average is “
+ battingAverage + “ There are “ + coundt + “ players”);
}
}
Public class TestPlayer
{
public static void main(String[] args)
{
Baseballplayer aCatcher = new
BaseballPlayer(12,.2218);
BaseballPlayer aShortstop = new
BaseballPlalyer(31, .385);
aCatcher.showPlayer();
aShortstop.showplayer();
BaseballPlayer anOutfielder = new
BaseballPlalyer(44, .505);
anOutfielder.showPlayer();
aCatcher.showPlayer();
}
}
OUTPUT
Player #12 batting average is .218 There are 2 players
Player #31 batting average is .385 There are 2 players
Player #44 batting average is .505 There are 3 players
Player #12 batting average is .218 There are 3 players
Constants
Literal strings are constants, like “First
Java Application”
 So are numbers, like 38.16
 These are literal constants


Variables, on the other hand, do change
Public class Student
{
private static final int SCHOOL_ID = 12345;
private int stuNum;
private double gpa;
public Student(int stuNum, double gpa)
{
this.stuNum = stuNum;
this.gpa = gpa;
}
public void showStudent ()
{
System.out.println(“Student #” + stuNum + “ gpa is
“ + gpa);
}
}
Notice the reserved word final

final indicates that a field value is
permanent.
The identifier SCHOOL_ID is a symbolic
constant
 For such it is customary to use all caps
and to include underscores between
words
 This helps us distinguish symbolic
constants from variables

Symbolic constants
You cannot change the value of a
symbolic constant after declaring it
 You must initialize a constant with a value



If a declared constant does not receive a
value at the time of its creation, it can never
receive a value
Using symbolic constants makes your
programs easier to understand, as
opposed to using the literal value
Automatically imported, prewritten
constants and methods
There are over 500 pre-written classes
that you can avail yourself of
 Re-use is the way to get time and cost
leverage in creating ‘new’ applications
 You have already used the System and
JOptionPane classes
 Each of these is stored in a package or
library of classes—a folder that provides a
convenient grouping for classes.

Importing packages
When you used the JOptionPane class
you had to import the java.swing package
into your program with the statement..
 Import javax.swing.JOptionPane;
 The class System does not have to be
imported

Math functions
Are available in the package
java.lang.Math
 Do not have to be imported
 All constants and methods in this package
are static—therefore, they are

Class variables
 Class methods

Examples of use..
areaOfCircle = java.lang.Math.Pi * radius *
radius;
 Or simply…
 areaOfCircle = Math.PI * radius * radius;
 Where
 Public final static double PI =
3.14159265357979323846;

Explicitly imported prewritten
classes and their methods
Only a few prewritten classes are included
in the programs you write, like those in the
System class and those in the java.lang
class
 The rest have to be imported, like
 Import javax.swing.JOptionPane;
 You can either import the entire class or
import the package in which the class is
contained

There are three ways to access
pre-written classes that are not
included automatically
1.
2.
3.
Use the entire path with the class name
Import the class
Import the package that contains the
class you are using
Consider the java.util class containing
the class GregorianCalendar
You can instantiate an object of type
GregorianClaenday from this class by
using the full class path, as in
Java.util.GregorianCalendar myAnniversary
= new java.util.GregorianCalendar();

Alternatively…
You can include an important statement
like
Import java.util.GregorianCalendar;

Then the declaration of the instance is
gregorianCalendar myAnniversary = new
GregorianCalendar();
Import statements must appear
where??

Before the first executable statement of
your java class file
As an alternative to importing a
class you can import an entire
package of classes
Instead of…
Import java.util.GregorianCalendar;

You can use
Import java.util.*;
imports all of the Java.util classes, not just the
GregorianCalendar class
Here you are use the * as a wildcard symbol
// AGE CALCULATOR
import java.util.*;
import javax.swing.*;
public class AgeCalculator
{
public static void main(String[] args)
{
GregorianCalendar now = new GregorianCalendar();
int nowYear;
int birthYear;
int yearsOld;
birthYear = Integer.parseInt(JOptionPane.showInputDialog(null,
"In what year were you born?"));
nowYear = now.get(Calendar.YEAR);
yearsOld = nowYear - birthYear;
JOptionPane.showMessageDialog(null,
"This is the year you become " + yearsOld + " years old");
System.exit(0);
}
}