1 / 24

Announcements

This lecture covers topics on static fields and methods, method invocations, and the conditional operator. It also explains the concept of static and its usage in Java.

rlockhart
Download Presentation

Announcements

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. Announcements • Homework P1 is due today • Homework P2 is due next Thursday • Your quizzes will be returned with P1 Lecture 8

  2. Today’s Topics • Review • Static Fields and Methods • Conditional Operator Lecture 8

  3. Review • Detailed explanation of method calls yesterday • What were the four steps that occur when a method is invoked? • What’s x++ mean? • x++ vs. x-- Lecture 8

  4. Why Static? • Suppose that we would like to maintain, somehow, the number of instances of Employee that were ever created. The following does not work!publicclass Employee {publicint noEmps= 0; //Number of Employees ever createdpublic String name;// Constructor -- An Employee named npublic Employee(String n) { noEmps= noEmps+1; name= n; }} Lecture 8

  5. Use “static” Using the prefix qualifier static means that there is only ONE field noEmps for the whole class, not one for each instance of the class:publicclass Employee {staticpublicint noEmps= 0; //Number Employees ever createdpublic String name; //Employee’s name// Constructor -- An Employee named npublic Employee(String n) { noEmps= noEmps+1; name= n;} // Return no. of Employees ever createdpublicint getNoEmps() {return noEmps;}} Lecture 8

  6. Example staticpublicvoid main (String args[ ]) { Employee v1= new Employee(“Millett”); System.out.println("No. of emps" + v1.noEmps); Employee v2= new Employee(“Ubik”); System.out.println("No. of emps" + v2.noEmps); } Lecture 8

  7. Picture of Previous Class Employee ----------------------------------------------------- noEmps _______ Name Millett Name Ubik Frame for main v1 ____ v2 ____ Lecture 8

  8. How this works • A static field (or method) is called a class variable (or method). • At runtime, a box for a class named C contains all the class variables and methods. Whenever an instance of class C is created, it is placed in this box. • A parameter or local variable declared as C v;is placed in the frame for the method in which it appears. • This model assures that the rule we gave for finding a variable, when it is referenced, works: look first in the frame for method being executed, then in the surrounding box, etc. Lecture 8

  9. In Practice. . . • You can (should) use the name of the class, instead of a class variable, to refer-ence a static field or methodEmployee v1= new Employee(“Millett”);Employe v2= new Employee(“Ubik”); • Instead of writingSystem.out.println(v1.noEmps);writeSystem.out.println(Employee.noEmps); Lecture 8

  10. Private and Static Make the static field private, so it can’t be changed from outside the class. Have a “get” method to read its value. publicclass Employee { staticprivateint noEmps= 0; //No. Empls ever created public String name; //Employee’s name // Constructor -- An Employee named n public Employee(String n) { noEmps= noEmps+1; name= n;} // Return no. of Employees ever created publicint getNoEmps() {return noEmps;} } Lecture 8

  11. Final and Static • Constants declared using modifier final also often declared using static. • Why? • The value of constants can’t be changed, so there might as well be only one value across all objects of the class • Constants cannot be declared inside a method. Lecture 8

  12. Review so far. . . • Local variables -- local to a particular method • cannot be declared static • Instance variables -- used in a particular object • Class variables -- shared among all instances of a class • changing the value here changes it for all instances of that class Lecture 8

  13. Static Methods • Referred to as a class method • Don’t have to declare and instantiate a particular object in order to invoke a class/static method • Static methods cannot reference instance variables -- only local variables, static fields and parameters Lecture 8

  14. So, why is main static? • main needs to be executable by the interpreter without instantiating an object from the class containing main • Many other static methods can be found in Java API Lecture 8

  15. Example of static method // Return the number of Employees ever created staticpublicint getNoEmps() {return noEmps;} // A static method may be called only using the class name. // It may not be called using a variable name. Employee v1= new Employee(“Millett”); // WRONG: System.out.println(v1.getNoEmps()); // RIGHT: System.out.println(Employee.getNoEmps()); Lecture 8

  16. Math class - lots of static methods publicfinalclass Math { publicstaticfinaldouble E = 2.7182818284590452354; publicstaticfinaldouble PI = 3.14159265358979323846; publicstaticnativedouble sin(double a); publicstaticnativedouble cos(double a); publicstaticint round(float a) { return (int)floor(a + 0.5f);} publicstaticint max(int a, int b) {return (a >= b) ? a : b;} Lecture 8

  17. How to call these methods? • Recall: Use class name not object name to call static methods: • double x = Math.sin(183.2); • double root = Math.sqrt(33); • int y = Math.max(5, 4); Lecture 8

  18. Where to find this stuff? • In folder: CodeWarrior / Java Support / java / lang • Poke around, don’t change anything. • One good place for Java docs: http://java.sun.com Lecture 8

  19. Conditional Operator • We call this a ternary operator (requires 3 operands) +, -, etc. are binary operators • Syntax: condition ? expression1 : expression2; • Sort of an abbreviated if-else statement • Use it sparingly. • expression1 and expression2 must evaluate to the same type Lecture 8

  20. Example of conditional operator total = (total > MAX) ? total + 1 : total + 2; is equivalent to: if (total > MAX) total = total + 1; else total = total + 2; Lecture 8

  21. Another example of ternary op int x; int y; x = Integer.parseInt(stdin.readLine()); y = Integer.parseInt(stdin.readLine()); System.out.println(“The largest of your inputs is ” + ((x >=y) ? x : y) ); Lecture 8

  22. Floats and Doubles • float -- 32 bits, double -- 64 bits • floats have only 7 significant digits, therefore, even though something like 49786.2123 is in range, you need to use a double • Java assumes all floating point literals (e.g. 34.65) are doubles. If you want a float, append ‘f’ as in 34.65f Lecture 8

  23. Precision in Java wrt floating point values • Do not use == to compare floating point values • Better way: if (Math.abs(f1 - f2) < TOLERANCE) System.out.println(“Pretty much equal.”); Lecture 8

  24. Wrapper classes • Each primitive has a wrapper class (already seen Integer and Double) • Available in java.lang package. • Objects created from these class can be useful for converting value of one type into another • Integer.parseInt(), Double.valueOf() are both static methods, for example • Check out Appendix O in your text Lecture 8

More Related