1 / 51

More Object Concepts—Farrell, Chapter 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.

bookerc
Download Presentation

More Object Concepts—Farrell, Chapter 4

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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

  3. 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

  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

  7. 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?

  8. 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

  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); }

  10. 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.

  11. 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

  12. 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.

  13. 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

  14. 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.

  15. 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

  16. Example Public class Employee { Private int empNum; Employee(int num) { empNum = num; } } Employee fullTimeWorker = new Employee(999) Employee partTimeWorker = new Employee(888)

  17. 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? Two

  18. One constructor with args, a second with none public class Employee { private int empNum; Employee(int num) { empNum = num; } Employee() { empNum = 999; } }

  19. 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 NO!

  20. 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()

  21. 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:

  22. The getEmpNum() Code Public int getEmpNum() { return this.empNum; } However, usually you don’t have to explicitly use the this keyword

  23. So the code can look like Public int getEmpNum() { return empNum; }

  24. 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); } }

  25. Public class TestStudent { public static void main(String[] args) { Student a PsychMajor = new Student(111,3.5); aPsychMajor.showStudent(); } }

  26. 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

  27. 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); } }

  28. 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

  29. 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

  30. class variables • Are shared, common to every instance of a class • Instance variables are separate for every instance of a class

  31. 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”); } }

  32. 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(); } }

  33. 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

  34. 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

  35. 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); } }

  36. 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

  37. 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

  38. 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.

  39. 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

  40. 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

  41. 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;

  42. 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

  43. There are three ways to access pre-written classes that are not included automatically • Use the entire path with the class name • Import the class • Import the package that contains the class you are using

  44. 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();

  45. Alternatively… • You can include an important statement like Import java.util.GregorianCalendar; Then the declaration of the instance is gregorianCalendar myAnniversary = new GregorianCalendar();

  46. Import statements must appear where?? • Before the first executable statement of your java class file

  47. 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

  48. // 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); } }

More Related