More Object Concepts— Farrell, Chapter 4 Dr. Burns.

51
More Object Concepts More Object Concepts —Farrell, Chapter 4 —Farrell, Chapter 4 Dr. Burns Dr. Burns

Transcript of More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Page 1: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

More Object Concepts—More Object Concepts—Farrell, Chapter 4Farrell, Chapter 4

Dr. BurnsDr. Burns

Page 2: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

OutlineOutline Blocks and ScopeBlocks and Scope Overload a MethodOverload a Method AmbiguityAmbiguity Send arguments to constructorsSend arguments to constructors Overload constructorsOverload constructors ThisThis Static variablesStatic variables ConstantsConstants Automatically imported, prewritten constants and Automatically imported, prewritten constants and

methodsmethods Explicitly imported prewritten classExplicitly imported prewritten class

Page 3: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Blocks and ScopeBlocks and ScopePublic static void methodWithNestedBlocks()Public static void methodWithNestedBlocks(){{ int aNumber = 10; // aNumber comes into existenceint aNumber = 10; // aNumber comes into existence

Ssytem.out.println(“In outer block, ANumber is “ + aNumber);Ssytem.out.println(“In outer block, ANumber is “ + aNumber);{{

int anotherNumber = 512;int anotherNumber = 512;// anotherNumber comes into existence// anotherNumber comes into existencesystem.out.println(“In inner block, aNumber is “ + system.out.println(“In inner block, aNumber is “ + aNumber + “ and another number is “ + aNumber + “ and another number is “ +

anotherNumber);anotherNumber);} } // anotherNumber ceases to exist// anotherNumber ceases to existSystem.out.println(“In outer block, aNumber is “ + aNumber);System.out.println(“In outer block, aNumber is “ + aNumber);

} // aNumber ceases to exist} // aNumber ceases to exist

Page 4: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Blocks and ScopeBlocks and Scope

Blocks must be completely nested within other Blocks must be completely nested within other blocksblocks

A local variable declared within an outer block A local variable declared within an outer block remains in scope anywhere within that blockremains in scope anywhere within that block

A local variable declared within an inner block A local variable declared within an inner block falls out of scope when control passes from that falls out of scope when control passes from that block and the variable ceases to existblock and the variable ceases to exist

Page 5: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Still more blocks and scopeStill more blocks and scope

Do not attempt to re-declare a local variable within Do not attempt to re-declare a local variable within an inner block, because that variable is still an inner block, because that variable is still activeactive

You cannot declare a variable more than once in a You cannot declare a variable more than once in a blockblock

You can use the same variable name within two You can use the same variable name within two blocks that are not nested—they occupy blocks that are not nested—they occupy different locations in memorydifferent locations in memory

Page 6: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Local variables….Local variables….

Always mask or hide other variables in a Always mask or hide other variables in a class that have the same nameclass that have the same name

Page 7: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

QuestionQuestion

An instance of a class gets created at the An instance of a class gets created at the point where the keyword point where the keyword newnew appears appears

Where does the instance get destroyed?Where does the instance get destroyed? If you exit a method that creates an object If you exit a method that creates an object

and later return to that method, will that and later return to that method, will that instance still be there?instance still be there?

Page 8: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Overload a MethodOverload a Method

Overloading a method means using the Overloading a method means using the same method name but with different args same method name but with different args and different definitions/declarations as and different definitions/declarations as wellwell

When you overload a Java method, you When you overload a Java method, you write multiple methods with the same write multiple methods with the same namename

Page 9: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

public static void calculateInterest(double public static void calculateInterest(double bal, double rate)bal, double rate)

{{Double interest;Double interest;

Interest = bal * rate;Interest = bal * rate;

System.out.println(“Simple interest on $” + bal + System.out.println(“Simple interest on $” + bal + “ at “ + rate + “% rate is “ + interest);“ at “ + rate + “% rate is “ + interest);

}}

Page 10: More Object Concepts— Farrell, Chapter 4 Dr. Burns.
Page 11: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

AmbiguityAmbiguity When an application contains just one version When an application contains just one version

of a method, you can call the method using a of a method, you can call the method using a parameter of the correct data type, on one that parameter of the correct data type, on one that can be promoted to the correct data type.can be promoted to the correct data type.

For example, assume a method has a single For example, assume a method has a single argument that has been declared to be argument that has been declared to be double. If, instead, an int is passed to the double. If, instead, an int is passed to the method, the int is cast as (promoted to) a method, the int is cast as (promoted to) a double and there is no compiler error.double and there is no compiler error.

Page 12: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

More AmbiguityMore Ambiguity

If a second method exists that will accept If a second method exists that will accept an int parameter, the compiler will use the an int parameter, the compiler will use the second method rather than casting the int second method rather than casting the int to a double and using the first method.to a double and using the first method.

This is called overloading of methods or This is called overloading of methods or method overloadingmethod overloading

Page 13: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

More AmbiguityMore Ambiguity

Consider two methods with two Consider two methods with two arguments. In the first method the arguments. In the first method the arguments are int and double; in the arguments are int and double; in the second method the arguments are double second method the arguments are double and int If you call this method with two int and int If you call this method with two int parameters, an ambiguous situation arises parameters, an ambiguous situation arises because there is not exact match for the because there is not exact match for the method call.method call.

Page 14: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

More ambiguityMore ambiguity

The compiler could promote the second int The compiler could promote the second int to a double and call the first method or to a double and call the first method or promote the first int to a double and call promote the first int to a double and call the second methodthe second method

This will not run problem-freeThis will not run problem-free

Page 15: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Send arguments to constructorsSend arguments to constructors

Recall that Java automatically provides a Recall that Java automatically provides a constructor method when you crease a constructor method when you crease a class. You can, however, provide your class. You can, however, provide your own constructor method if you’d like to own constructor method if you’d like to initialize your fields to something other initialize your fields to something other than the default initializations.than the default initializations.

Page 16: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

When you write your own When you write your own constructor…constructor…

You can provide for arguments or You can provide for arguments or parameters that are often used to pass parameters that are often used to pass initialization valuesinitialization values

Suppose that full-time employees have a Suppose that full-time employees have a field called empNum that is initialized to field called empNum that is initialized to 999, but part-time employees have an 999, but part-time employees have an empNum that is initialized to 888empNum that is initialized to 888

Page 17: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

ExampleExample

Public class EmployeePublic class Employee{{

Private int empNum;Private int empNum;Employee(int num)Employee(int num){{

empNum = num;empNum = num;

}}

}}

Employee fullTimeWorker = new Employee(999)Employee fullTimeWorker = new Employee(999)Employee partTimeWorker = new Employee(888)Employee partTimeWorker = new Employee(888)

Page 18: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Overload constructorsOverload constructors

This is just several different constructors This is just several different constructors with different arguments types in eachwith different arguments types in each

Analogous to overload methodsAnalogous to overload methodsTwo use this capability, you have to Two use this capability, you have to

explicitly define at least how many explicitly define at least how many constructors?constructors?

Page 19: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

One constructor with args, a One constructor with args, a second with nonesecond with none

public class Employeepublic class Employee{{

private int empNum;private int empNum;Employee(int num)Employee(int num){{

empNum = num;empNum = num;}}Employee()Employee(){{

empNum = 999;empNum = 999;}}

}}

Page 20: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

thisthis

When you create 200 instantiations of a When you create 200 instantiations of a class, you get 200 instantiations of the class, you get 200 instantiations of the data fields (variables) in the classdata fields (variables) in the class

Do you get 200 instantiations of the Do you get 200 instantiations of the methods in the class???methods in the class???

Only the class itself maintains the methodsOnly the class itself maintains the methods

Page 21: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

More of thisMore of this

Suppose you need the empNum of employee Suppose you need the empNum of employee worker--the code isworker--the code isInt employeeNumber = aWorker.getempNum();Int employeeNumber = aWorker.getempNum();

This uses the employee class getempNum() method This uses the employee class getempNum() method and it gets the employee number from the instance and it gets the employee number from the instance aWorkeraWorker

The compiler figures out whose employee number is to The compiler figures out whose employee number is to retrieved by the single method getempNum()retrieved by the single method getempNum()

Page 22: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Still more of thisStill more of this

You implicitly passed a reference You implicitly passed a reference (address) to the employee getempNum() (address) to the employee getempNum() method by use of the aWorkermethod by use of the aWorker

The method actually implements code that The method actually implements code that looks as follows:looks as follows:

Page 23: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

The getEmpNum() CodeThe getEmpNum() Code

Public int getEmpNum()Public int getEmpNum()

{{

return this.empNum;return this.empNum;

}}

However, usually you don’t have to explicitly However, usually you don’t have to explicitly use the use the thisthis keyword keyword

Page 24: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

So the code can look likeSo the code can look like

Public int getEmpNum()Public int getEmpNum()

{{

return empNum;return empNum;

}}

Page 25: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

public class Studentpublic class Student{{

private int stuNum;private int stuNum;private double gpa;private double gpa;Public Student(int stuNum, double gpa)Public Student(int stuNum, double gpa){{

stuNum = stuNum;stuNum = stuNum;gpa = gpa;gpa = gpa;

}}Public void showStudent()Public void showStudent(){{

System.out.printlin(“Student #” + stuNum + “ gpa is “ + gpa);System.out.printlin(“Student #” + stuNum + “ gpa is “ + gpa);}}

}}

Page 26: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Public class TestStudentPublic class TestStudent

{{

public static void main(String[] args)public static void main(String[] args)

{{

Student a PsychMajor = new Student a PsychMajor = new Student(111,3.5);Student(111,3.5);

aPsychMajor.showStudent();aPsychMajor.showStudent();

}}

}}

Page 27: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

The result here is…The result here is…

Student #0 gpa is 0.0Student #0 gpa is 0.0Not what we wanted…Not what we wanted…The compiler treatsThe compiler treats

stuNum = stuNum;stuNum = stuNum;

gpa = gpa;gpa = gpa;

As local variable = local variableAs local variable = local variable

Page 28: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

public class Studentpublic class Student{{

private int stuNum;private int stuNum;private double gpa;private double gpa;Public Student(int stuNum, double gpa)Public Student(int stuNum, double gpa){{

thisthis.stuNum = stuNum;.stuNum = stuNum;thisthis.gpa = gpa;.gpa = gpa;

}}Public void showStudent()Public void showStudent(){{

System.out.println(“Student #” + stuNum + “ gpa is “ + gpa);System.out.println(“Student #” + stuNum + “ gpa is “ + gpa);}}

}}

Page 29: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

The result here is…The result here is…

Student #111 gpa is 3.5Student #111 gpa is 3.5

Here, the use of Here, the use of thisthis must be explicit, must be explicit, because the use of because the use of thisthis causes the causes the compiler to understand compiler to understand

class variable = local variableclass variable = local variable

Which is what we wantWhich is what we want

Page 30: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

static variables are class variablesstatic variables are class variables

Class methods have no objects associated Class methods have no objects associated with them and cannot use a with them and cannot use a thisthis reference; reference; they are declared staticthey are declared static

Class methods, such as main are static, Class methods, such as main are static, they can not be used in conjunction with they can not be used in conjunction with instance objectsinstance objects

Conversely, we should not declare Conversely, we should not declare methods of classes that will be instantiated methods of classes that will be instantiated as staticas static

Page 31: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

class variablesclass variables

Are shared, common to every instance of Are shared, common to every instance of a classa class

Instance variables are separate for every Instance variables are separate for every instance of a classinstance of a class

Page 32: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Public class BaseballPlayerPublic class BaseballPlayer{{

private static int count = 0;private static int count = 0;private int number;private int number;private double batttingAverage;private double batttingAverage;public BaseballPlayer(ind id, double avg)public BaseballPlayer(ind id, double avg){{number = id;number = id;battingAverage = avg;battingAverage = avg;count = count + 1;count = count + 1;}}Public void showPlayer()Public void showPlayer(){{System.out.println(“Player #” + number + “ batting average is “ System.out.println(“Player #” + number + “ batting average is “ + battingAverage + “ There are “ + coundt + “ players”);+ battingAverage + “ There are “ + coundt + “ players”);}}

}}

Page 33: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Public class TestPlayerPublic class TestPlayer{{

public static void main(String[] args)public static void main(String[] args){{

Baseballplayer aCatcher = new Baseballplayer aCatcher = new BaseballPlayer(12,.2218);BaseballPlayer(12,.2218);

BaseballPlayer aShortstop = new BaseballPlayer aShortstop = new BaseballPlalyer(31, .385);BaseballPlalyer(31, .385);aCatcher.showPlayer();aCatcher.showPlayer();aShortstop.showplayer();aShortstop.showplayer();BaseballPlayer anOutfielder = new BaseballPlayer anOutfielder = new BaseballPlalyer(44, .505);BaseballPlalyer(44, .505);anOutfielder.showPlayer();anOutfielder.showPlayer();aCatcher.showPlayer();aCatcher.showPlayer();}}

}}

Page 34: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

OUTPUTOUTPUT

Player #12 batting average is .218 There are 2 playersPlayer #12 batting average is .218 There are 2 players

Player #31 batting average is .385 There are 2 playersPlayer #31 batting average is .385 There are 2 players

Player #44 batting average is .505 There are 3 playersPlayer #44 batting average is .505 There are 3 players

Player #12 batting average is .218 There are 3 playersPlayer #12 batting average is .218 There are 3 players

Page 35: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

ConstantsConstants

Literal strings are constants, like “First Literal strings are constants, like “First Java Application”Java Application”

So are numbers, like 38.16So are numbers, like 38.16These are literal constantsThese are literal constants

Variables, on the other hand, do changeVariables, on the other hand, do change

Page 36: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Public class StudentPublic class Student{{

private static private static finalfinal int SCHOOL_ID = 12345; int SCHOOL_ID = 12345;private int stuNum;private int stuNum;private double gpa;private double gpa;public Student(int stuNum, double gpa)public Student(int stuNum, double gpa){{this.stuNum = stuNum;this.stuNum = stuNum;this.gpa = gpa;this.gpa = gpa;}}public void showStudent ()public void showStudent (){{

System.out.println(“Student #” + stuNum + “ gpa System.out.println(“Student #” + stuNum + “ gpa is “ + gpa);is “ + gpa);}}

}}

Page 37: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Notice the reserved word Notice the reserved word finalfinal

finalfinal indicates that a field value is indicates that a field value is permanent.permanent.

The identifier SCHOOL_ID is a symbolic The identifier SCHOOL_ID is a symbolic constantconstant

For such it is customary to use all caps For such it is customary to use all caps and to include underscores between and to include underscores between wordswords

This helps us distinguish symbolic This helps us distinguish symbolic constants from variablesconstants from variables

Page 38: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Symbolic constantsSymbolic constants

You cannot change the value of a You cannot change the value of a symbolic constant after declaring itsymbolic constant after declaring it

You must initialize a constant with a valueYou must initialize a constant with a value If a declared constant does not receive a If a declared constant does not receive a

value at the time of its creation, it can never value at the time of its creation, it can never receive a valuereceive a value

Using symbolic constants makes your Using symbolic constants makes your programs easier to understand, as programs easier to understand, as opposed to using the literal valueopposed to using the literal value

Page 39: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Automatically imported, prewritten Automatically imported, prewritten constants and methodsconstants and methods

There are over 500 pre-written classes There are over 500 pre-written classes that you can avail yourself ofthat you can avail yourself of

Re-use is the way to get time and cost Re-use is the way to get time and cost leverage in creating ‘new’ applicationsleverage in creating ‘new’ applications

You have already used the System and You have already used the System and JOptionPane classesJOptionPane classes

Each of these is stored in a package or Each of these is stored in a package or library of classes—a folder that provides a library of classes—a folder that provides a convenient grouping for classes.convenient grouping for classes.

Page 40: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Importing packagesImporting packages

When you used the JOptionPane class When you used the JOptionPane class you had to import the java.swing package you had to import the java.swing package into your program with the statement..into your program with the statement..

Import javax.swing.JOptionPane;Import javax.swing.JOptionPane;The class System does not have to be The class System does not have to be

importedimported

Page 41: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Math functions Math functions

Are available in the package Are available in the package java.lang.Mathjava.lang.Math

Do not have to be importedDo not have to be importedAll constants and methods in this package All constants and methods in this package

are static—therefore, they areare static—therefore, they areClass variablesClass variablesClass methodsClass methods

Page 42: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Examples of use..Examples of use..

areaOfCircle = java.lang.Math.Pi * radius * areaOfCircle = java.lang.Math.Pi * radius * radius;radius;

Or simply…Or simply…areaOfCircle = Math.PI * radius * radius;areaOfCircle = Math.PI * radius * radius;WhereWherePublic final static double PI = Public final static double PI =

3.14159265357979323846;3.14159265357979323846;

Page 43: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Explicitly imported prewritten Explicitly imported prewritten classes and their methodsclasses and their methods

Only a few prewritten classes are included Only a few prewritten classes are included in the programs you write, like those in the in the programs you write, like those in the System class and those in the java.lang System class and those in the java.lang classclass

The rest have to be imported, likeThe rest have to be imported, like Import javax.swing.JOptionPane;Import javax.swing.JOptionPane;You can either import the entire class or You can either import the entire class or

import the package in which the class is import the package in which the class is containedcontained

Page 44: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

There are three ways to access There are three ways to access pre-written classes that are not pre-written classes that are not

included automaticallyincluded automatically

1.1. Use the entire path with the class nameUse the entire path with the class name

2.2. Import the classImport the class

3.3. Import the package that contains the Import the package that contains the class you are usingclass you are using

Page 45: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Consider the java.util class containing Consider the java.util class containing the class GregorianCalendarthe class GregorianCalendar

You can instantiate an object of type You can instantiate an object of type GregorianClaenday from this class by GregorianClaenday from this class by using the full class path, as inusing the full class path, as in

Java.util.GregorianCalendar myAnniversary Java.util.GregorianCalendar myAnniversary = new java.util.GregorianCalendar();= new java.util.GregorianCalendar();

Page 46: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Alternatively…Alternatively…

You can include an important statement You can include an important statement likelike

Import java.util.GregorianCalendar;Import java.util.GregorianCalendar;

Then the declaration of the instance isThen the declaration of the instance is

gregorianCalendar myAnniversary = new gregorianCalendar myAnniversary = new GregorianCalendar();GregorianCalendar();

Page 47: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Import statements must appear Import statements must appear where??where??

Before the first executable statement of Before the first executable statement of your java class fileyour java class file

Page 48: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

As an alternative to importing a As an alternative to importing a class you can import an entire class you can import an entire

package of classespackage of classes

Instead of…Instead of…Import java.util.GregorianCalendar;Import java.util.GregorianCalendar;

You can useYou can useImport java.util.*;Import java.util.*;imports all of the Java.util classes, not just the imports all of the Java.util classes, not just the

GregorianCalendar classGregorianCalendar classHere you are use the * as a wildcard symbolHere you are use the * as a wildcard symbol

Page 49: More Object Concepts— Farrell, Chapter 4 Dr. Burns.

// AGE CALCULATOR// AGE CALCULATOR

import java.util.*;import java.util.*;import javax.swing.*;import javax.swing.*;public class AgeCalculatorpublic class AgeCalculator{{ public static void main(String[] args)public static void main(String[] args) {{ GregorianCalendar now = new GregorianCalendar();GregorianCalendar now = new GregorianCalendar(); int nowYear;int nowYear; int birthYear;int birthYear; int yearsOld;int yearsOld; birthYear = Integer.parseInt(JOptionPane.showInputDialog(null, birthYear = Integer.parseInt(JOptionPane.showInputDialog(null,

"In what year were you born?"));"In what year were you born?")); nowYear = now.get(Calendar.YEAR);nowYear = now.get(Calendar.YEAR); yearsOld = nowYear - birthYear;yearsOld = nowYear - birthYear; JOptionPane.showMessageDialog(null,JOptionPane.showMessageDialog(null, "This is the year you become " + yearsOld + " years old");"This is the year you become " + yearsOld + " years old"); System.exit(0);System.exit(0); }}}}

Page 50: More Object Concepts— Farrell, Chapter 4 Dr. Burns.
Page 51: More Object Concepts— Farrell, Chapter 4 Dr. Burns.