Download presentation
Presentation is loading. Please wait.
Published byElizabeth Carson Modified over 9 years ago
1
More Object Concepts— Farrell, Chapter 4 Dr. Burns
2
Outline Blocks and Scope Blocks and Scope Overload a Method Overload a Method Ambiguity Ambiguity Send arguments to constructors Send arguments to constructors Overload constructors Overload constructors This This Static variables Static variables Constants Constants Automatically imported, prewritten constants and methods Automatically imported, prewritten constants and methods Explicitly imported prewritten class Explicitly imported prewritten class
3
Blocks and Scope Public static void methodWithNestedBlocks() { int aNumber = 10; // aNumber comes into existence 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
4
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
5
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
6
Local variables…. Always mask or hide other variables in a class that have the same name Always mask or hide other variables in a class that have the same name
7
Question An instance of a class gets created at the point where the keyword new appears An instance of a class gets created at the point where the keyword new appears Where does the instance get destroyed? 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? If you exit a method that creates an object and later return to that method, will that instance still be there?
8
Overload a Method Overloading a method means using the same method name but with different args and different definitions/declarations as well 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 When you overload a Java method, you write multiple methods with the same name
9
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); }
11
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. 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. 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.
12
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. 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 This is called overloading of methods or method overloading
13
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. 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.
14
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 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 This will not run problem-free
15
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. 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.
16
When you write your own constructor… You can provide for arguments or parameters that are often used to pass initialization values 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 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
17
Example Public class Employee { Private int empNum; Employee(int num) { empNum = num; }} Employee fullTimeWorker = new Employee(999) Employee partTimeWorker = new Employee(888)
18
Overload constructors This is just several different constructors with different arguments types in each This is just several different constructors with different arguments types in each Analogous to overload methods Analogous to overload methods Two use this capability, you have to explicitly define at least how many constructors? Two use this capability, you have to explicitly define at least how many constructors?
19
One constructor with args, a second with none public class Employee { private int empNum; Employee(int num) { empNum = num; }Employee(){ empNum = 999; }}
20
this When you create 200 instantiations of a class, you get 200 instantiations of the data fields (variables) in the class 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??? Do you get 200 instantiations of the methods in the class??? Only the class itself maintains the methods Only the class itself maintains the methods
21
More of this Suppose you need the empNum of employee worker--the code is 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()
22
Still more of this You implicitly passed a reference (address) to the employee getempNum() method by use of the aWorker 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 method actually implements code that looks as follows:
23
The getEmpNum() Code Public int getEmpNum() { return this.empNum; } However, usually you don’t have to explicitly use the this keyword
24
So the code can look like Public int getEmpNum() { return empNum; }
25
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); }}
26
Public class TestStudent { public static void main(String[] args) { Student a PsychMajor = new Student(111,3.5); aPsychMajor.showStudent();}}
27
The result here is… Student #0 gpa is 0.0 Student #0 gpa is 0.0 Not what we wanted… Not what we wanted… The compiler treats The compiler treats stuNum = stuNum; gpa = gpa; As local variable = local variable
28
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); }}
29
The result here is… Student #111 gpa is 3.5 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
30
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 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 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 Conversely, we should not declare methods of classes that will be instantiated as static
31
class variables Are shared, common to every instance of a class Are shared, common to every instance of a class Instance variables are separate for every instance of a class Instance variables are separate for every instance of a class
32
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”); }}
33
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();}}
34
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
35
Constants Literal strings are constants, like “First Java Application” Literal strings are constants, like “First Java Application” So are numbers, like 38.16 So are numbers, like 38.16 These are literal constants These are literal constants Variables, on the other hand, do change Variables, on the other hand, do change
36
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); }}
37
Notice the reserved word final final indicates that a field value is permanent. final indicates that a field value is permanent. The identifier SCHOOL_ID is a symbolic constant The identifier SCHOOL_ID is a symbolic constant For such it is customary to use all caps and to include underscores between words For such it is customary to use all caps and to include underscores between words This helps us distinguish symbolic constants from variables This helps us distinguish symbolic constants from variables
38
Symbolic constants You cannot change the value of a symbolic constant after declaring it You cannot change the value of a symbolic constant after declaring it You must initialize a constant with a value 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 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 Using symbolic constants makes your programs easier to understand, as opposed to using the literal value
39
Automatically imported, prewritten constants and methods There are over 500 pre-written classes that you can avail yourself of 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 Re-use is the way to get time and cost leverage in creating ‘new’ applications You have already used the System and JOptionPane classes 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. Each of these is stored in a package or library of classes—a folder that provides a convenient grouping for classes.
40
Importing packages When you used the JOptionPane class you had to import the java.swing package into your program with the statement.. When you used the JOptionPane class you had to import the java.swing package into your program with the statement.. Import javax.swing.JOptionPane; Import javax.swing.JOptionPane; The class System does not have to be imported The class System does not have to be imported
41
Math functions Are available in the package java.lang.Math Are available in the package java.lang.Math Do not have to be imported Do not have to be imported All constants and methods in this package are static—therefore, they are All constants and methods in this package are static—therefore, they are Class variables Class variables Class methods Class methods
42
Examples of use.. areaOfCircle = java.lang.Math.Pi * radius * radius; areaOfCircle = java.lang.Math.Pi * radius * radius; Or simply… Or simply… areaOfCircle = Math.PI * radius * radius; areaOfCircle = Math.PI * radius * radius; Where Where Public final static double PI = 3.14159265357979323846; Public final static double PI = 3.14159265357979323846;
43
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 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 The rest have to be imported, like Import javax.swing.JOptionPane; Import javax.swing.JOptionPane; You can either import the entire class or import the package in which the class is contained You can either import the entire class or import the package in which the class is contained
44
There are three ways to access pre-written classes that are not included automatically 1. Use the entire path with the class name 2. Import the class 3. Import the package that contains the class you are using
45
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 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();
46
Alternatively… You can include an important statement like You can include an important statement like Import java.util.GregorianCalendar; Then the declaration of the instance is gregorianCalendar myAnniversary = new GregorianCalendar();
47
Import statements must appear where?? Before the first executable statement of your java class file Before the first executable statement of your java class file
48
As an alternative to importing a class you can import an entire package of classes Instead of… 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
49
// AGE CALCULATOR import java.util.*; import javax.swing.*; public 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, "In what year were you born?")); birthYear = Integer.parseInt(JOptionPane.showInputDialog(null, "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); }}
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.