Download presentation
Presentation is loading. Please wait.
1
More on Objects and Classes
Static Methods in Object Classes, Overloading, the toString Method Sections 6.1, 6.2, 6.4
2
Overview Review of data-type classes
Class constants and the meaning of static Static methods private or public Making objects easier to use “virtualˮ getters automatic numbering secondary constructors overloading and “defaultˮ arguments the toString method
3
Reminder We are now creating projects with more than one class/file in them program class has main method in it its methods are static data type class has no main method in it its methods are (mostly) not static Colour of code shows which class it’s in: program class code will be in blue data type class code will be in brown
4
Previously Creating objects Using methods Creating our own methods
Scanner kbd = new Scanner(System.in); Using methods System.out.println("Hi"); n = kbd.nextInt(); Creating our own methods printIntroduction(); cm = feetAndInchesToCM(5, 7.5); Creating our own data types Student stu = new Student("A ", "Stu Dent", 0);
5
Classes and Data Data type classes designed to hold data:
Student s1; Rectangle r1; s1 = new Student("A ", "Dent, Stu", 85); r1 = new Rectangle(1.5, 7.2); Can access and (sometimes) change the data Sopln(s1.getName() + " got " + s1.getGrade() + "%."); s1.setGrade(100); Sopln(r1.getHeight() + "x" + r1.getWidth() + " rectangle"); Remember to replace Sopln with System.out.println!
6
Instance Variables Variables to hold the data for this object
private String name; private int pctGrade; declared private; not static protects the data in the field from other classes only Student objects have direct access others must ask to see or change its value public final String A_NUMBER; instance constants declared public final; not static don’t need to protect it; no one can change it Instance variables also known as fields or properties.
7
Constructor Method to give fields their first value
based on what client asks for public Student(String a, String n, int g) { aNumber = a; name = n; if (0 <= g && g <= 100) { pctGrade = g; } else { pctGrade = 0; } Parameters: values the client requested Use those values… Unless they don't make sense Assign values to instance variables Purpose of constructor is to give values to fields.
8
Getters and Setters Methods using the object’s values
getters return the value to the client String s1Name = s1.getName(); setters ask object to change value s1.setGrade(100); object might not want to make the change s2.setGrade(1000); which is why we make instance variables private! which (in turn) is why we need getters and setters
9
Using Instance Variables
Can be used only in instance methods just say the name: public String getName() { return name; } optionally put this. in front of the field’s name: public void setName(String newName) { this.name = newName; generally don’t bother!
10
Choosing Not to Change a Value
Check whether the change makes sense grades must be ! public void setGrade(int newGrade) { if (0 <= grade && grade <= 100) { grade = newGrade; } else { // throw an exception or print an error message… // …or sometimes just quietly ignore it (silent failure) }
11
More Instance Methods Maybe a (void) method to print out all info
it’s just nice to have stu.printRecord(); public void printRecord() { Sopln("Number: " + A_NUMBER); Sopln("Name: " + name); Sopln("Grade: " + grade + "%"); } Number: A Name: Dent, Stu Grade: 100% Remember to replace Sopln with System.out.println!
12
A Multi-Setter Sometimes want to change multiple values
r1.setHeight(2.0); r1.setWidth(5.0); makes Rectangle class more convenient to use Make the method; have it call the other setters public void setSize(double reqHgt, double reqWid) { setHeight(reqHgt); // optionally: this.setHeight(…) setWidth(reqWid); // optionally: this.setWidth(…) } r1.setSize(2.0, 5.0); setHeight and setWidth called on same object as setSize was
13
What is “this”? “this” is each Java object’s name for itself
this.name my name this.setName(n) set my name to n “this” is almost always optional! name (my) name setName(n) set (my) name to n only needed for disambiguation public void setName(String name) { this.name = name; } “name” here is the parameter so need this. to make sure Java sets my name
14
Magic Numbers in Student
We are using the number 100 in Student.java highest possible grade used in constructor and in setGrade Name the numbers you use! declare them as class constants: public static final int MAX_GRADE = 100; final prevent accidental changes public no need to protect constants from others static (?!?)
15
What Does “staticˮ Mean?
Programs use static methods: main and all its helpers Data types generally don’t: fields, constructor, getters, setters, other… But MAX_GRADE is static… …because every Student has same max grade static same value for every object in this class same value even if there are no objects! non-static each object has its own value
16
Individual or Shared? static shared by all objects
public class Student { // every Student has same maximum grade public static final int MAX_GRADE = 100; // each Student has their own ANumber, name and grade public final String A_NUMBER; private String name; private int grade; … }
17
Individual or Shared? static shared by all objects Student stu1 stu2
A_NUMBER name grade A stu1 Dent, Stu 80 MAX_GRADE 100 A_NUMBER name grade A stu2 Tudiante, A. 85 A_NUMBER name grade A stu3 Student, Lowell E. 80
18
Using a Class Constant Doesn’t matter which Student you ask
ask yourself (this.MAX_GRADE) ask class (Student.MAX_GRADE) or just use the name (MAX_GRADE) if (0 <= g && g <= MAX_GRADE) { grade = g; } need that code in both constructor and setter hmmm…
19
Class (static) Methods
Ask if a grade is a valid grade if (isValidGrade(g)) { pctGrade = g; } use that code in the constructor and in setGrade doesn’t matter who you ask, answer is same static method! private static boolean isValidGrade(int g) { return (0 <= g && g <= MAX_GRADE);
20
Exercise Modify the isValidGrade method so that the negative of MAX_GRADE is a valid grade private static boolean isValidGrade(int g) { return (0 <= g && g <= MAX_GRADE); } note that constructor and setter won’t need to change! both use isValidGrade to tell them if a grade is valid
21
Public static Methods May want a static method to be public
public other classes can call this method OK for other classes to get the information? OK for a program to ask if a grade is valid? could do its own error checking might be good! public static boolean isValidGrade(int g) { … } Stay private unless good reason to be public but such good reasons are common
22
Calling a public static Method
Can be called from a program should be called using class name can be called using a Student object; but don’t Sop("Enter your grade: "); g = kbd.nextInt(); kbd.nextLine(); while (!Student.isValidGrade(g)) { Sopln("That's not a valid grade!"); g = kbd.nextInt(); kbd.nextLine(); } s1.setGrade(g); // guaranteed to be a valid grade
23
Exercise Create a class method that will tell you what the letter grade is, given a percent grade String letGr1= Student.letterGradeFor(100); // A String letGr2 = Student.letterGradeFor(72); // B where 0..49 "F" "D" "C" "B" "A"
24
Another Instance Method
Now that we have a class method to translate numbers to letters, client can ask: String s1Letter = Student.letterGradeFor(s1.getGrade()); But that’s awkward. Nicer would be: String s1Letter = s1.getLetterGrade(); which is easy to write just return the letter grade for this one’s pct grade
25
getLetterGrade An instance method a sort of “getter”
public String getLetterGrade() { return Student.letterGradeFor(this.pctGrade); } Note: there is NO letterGrade inst. var. object just calculates it when it’s asked for it that’s a GOOD THING why?
26
getLetterGrade Calculating letter grade as needed is good
consider this code: Student s = new Student("Dent, Stu", 0); s.setGrade(90); Sopln(s.getLetterGrade()); what should get printed? what does get printed if… constructor sets letterGrade to F, and setGrade doesn’t change letterGrade?
27
Programming Principles
Make it impossible (or very hard) for the client to do stupid/malicious things can’t set grade outside can’t set grade to 100 and letterGrade to F Make it easy for client to do common things ask a Student for their letter grade, even tho’ could ask Student for their grade and then translate it using “cascading if” control getLetterGrade is a convenience
28
Exercise Create a getArea method for Rectangles
area of rectangle is length times width public class Rectangle { private double height; private double width; … } What instance variables do you need to add? Are you sure????
29
About Student Number Should always be in same format
A + 8 digits Could check to see if it’s in that format… it’s not very hard, actually …but it might be better to do that ourselves get a number and format it using “A%08d” Student s1 = new Student(1234, "Dent, Stu", 80); But there’s another problem…
30
Student Numbers Student number identifies the student
our constructor allows two students to have the same student number! Student pat = new Student(1234, "Pat", 82); Student chris = new Student(1234, "Chris", 14); Better if we choose the student number we = the people writing the Student class so that no two students get the same one Student pat = new Student("Pat", 82); // automatic A# Student chris = new Student("Chris", 14); // auto A#
31
Student Numbers We will number our students, starting at 1
first student gets student number 1 second student gets student number 2 … Need to track what student number we’re at which student will keep track? none of them! the class will keep track – static variable
32
Assigning Student Numbers
static variable belongs to class non-static variables / constants belong to objects A_NUMBER A stu1 A_NUMBER A stu2 nextANumber 1 Student 4 3 2 A_NUMBER A stu3
33
Class (static) Variables
public class Student { public final String A_NUMBER; private String name; private int pctGrade; private static int nextANumber = 1; nextANumber belongs to Student class not to each Student, but to every Student but it’s not final: changes with each new Student
34
Static vs. Non-Static Keyword static used to say that it belongs to the class instead of the instance static “unchanging” Can be used in constants & variables private static final double CM_PER_INCH = 2.54; private static int nextANumber = 1; all objects (in the class where it’s declared) share this one constant/variable
35
Static vs. Non-Static Without static, field belongs to the instance
can have non-static constants and variables public final String A_NUMBER; private String name; private int grade; each object (in the class where it’s declared) gets its own version of these fields
36
Static vs. Final “static” and “final” both mean unchanging
final unchanging over time every time you look, it’ll be the same static unchanging over objects every object you look at will have the same Can use one, other, both, neither private int iv = 1; // instance variable private static int cv = 1; // class variable private final int IC = 1; // instance constant private static final int CC = 1; // class constant
37
Assigning Student Numbers
To create a student: assign the next available number update the next available number (continue setting other IVs) public Student(String n, int g) { A_NUMBER = String.format("A%08d", nextANumber); ++nextANumber; … }
38
Another Convenience Student grades start off at 0, usually
make it easy for client to create a student with grade set to 0 Student s = new Student("Tudiaunt, A."); grade not specified, so set it to 0 add another constructor! you can have more than one! this constructor takes only one String (no int) “overloaded” constructor
39
Overloading Constructors
Create as many constructors as you want! public class Thing { public Thing(String a, int c) {} public Thing(String a, String b) {} public Thing(String a, String b, int c) {} } Java will figure out which one to use so long as it can tell them apart! won’t let you create two that it can’t tell apart
40
Which Constructor? Choice based on arguments
Student s1 = new Student("Pat", 100); chooses Student(String n, int g) Student s2 = new Student("Chris"); chooses Student(String n) Can’t have constructors with same arguments public Person(String firstName, String lastName) {} public Person(String lastName, String firstName) {} Java can’t tell them apart! Person p = new Person("Mackenzie", "Ryan");
41
Exercise Given these constructors Which constructor gets called?
public Thing() public Thing(String a, int c) public Thing(String a, String b) public Thing(String a, String b, int c) Which constructor gets called? Thing thing1 = new Thing("Cat", "Hat"); Thing thing2 = new Thing("Thing", 2); Thing thing3 = new Thing();
42
Missing Arguments Normal Thing constructor has three arguments
t1 = new Thing("Cat", "Hat", 42); Other constructors are missing arguments: t2 = new Thing("Cat", "Hat"); // int missing t3 = new Thing("Thing", 1); // String missing t4 = new Thing(); // everything missing! No particular field values requested but we still need to give fields values! what values do we give?
43
Missing Arguments Normal Thing constructor has three arguments
t1 = new Thing("Cat", "Hat", 42); Missing values should be filled in: t2 = new Thing("Cat", "Hat"); // missing int 0 t3 = new Thing("Thing", 1); // missing String "" // but which String is missing??? t4 = new Thing(); // becomes ("", "", 0) You decide, based on what makes sense what grade for a Student when no grade requested? what do most Students’ grades start out as?
44
Secondary Constructors
Our original constructor works OK want our new constructors to work just as well could copy and paste code… …but it’s better to call code less work to change it later! want to call our first constructor, adding a 0 Student("Pat") same as Student("Pat", 0) so tell Student(String) to call Student(String, int) (with the int argument set to zero)
45
Programming Principle: Don’t Copy Code
Copying code considered dangerous code may need to change copied code needs to be changed in every place not changed bug creeps in As much as possible, call code a method to do what needs doing set this student’s number & calculate next only needs to be changed in one place
46
Calling a Constructor Special way to do it:
use “this” instead of “Student” (class name) public Student(String n) { this(n, 0); // make this with that name and grade of 0 } Note: no “new”, either Note: nor “return” Note the arguments: String and int calls Student(String n, int g), with g set to 0
47
Constructor Calling Client uses one argument constructor
n = "Chris" n = "Chris", g = 0 Client uses one argument constructor Student s = new Student("Chris"); Java starts one-argument constructor public Student(String n) { n is “Chris” this(n, 0); one-argument constructor calls two-argument public Student(String n, pctGrade g) { n is “Chris”, g is 0 2-arg constructor does what needs doing
48
Secondary Constructors
For now: one constructor is the primary constructor the one that has arguments for all settable IVs it does all the work other constructors just call the primary one one line: this(…) fill in a value for each settable IV that’s missing
49
Exercise This constructor is defined: Write new constructors:
public Thing(String a, String b, int c) Write new constructors: t1 = new Thing("aVal", 10); // missing b "" :. same as Thing("aVal", "", 10) t2 = new Thing("aVal", "bVal"); // missing c 0 :. same as Thing("aVal", "bVal", 0) t3 = new Thing(); // missing a "aVal", b "", c 0 :. same as Thing("Undefined", "", 0)
50
Overloading Methods Can do the same for other methods
methods with same name, different parameters System.out.println("Hello!"); // String System.out.println(42); // int System.out.println(); // (nothing) decide which ones you want and define them make one of them your primary version… … rest are secondary (call the primary version)
51
Recall The method drawRectangle(int h, int w) method call
public static void drawRectangle(int rows, int cols) { for (int r = 1; r <= rows; ++r) { for (int c = 1; c <= cols; ++c) { System.out.print("*"); } System.out.println(); method call Shapes.drawRectangle(4, 7); *******
52
New/Improved Method Say what character to print
Say what character to print Shapes.drawRectangle(4, 7, '+'); Code very similar to before public static void drawRectangle(int rows, int cols, char ch) { for (int r = 1; r <= rows; ++r) { for (int c = 1; c <= cols; ++c) { System.out.print(ch); } System.out.println();
53
Change Old Method Old version uses ‘*’ as the character to print
improved method can print any character call the new & improved method Tell the new/improved public static void drawRectangle(int rows, int cols) { Shapes.drawRectangle(rows, cols, '*'); } Shapes.drawRectangle(4, 7); *******
54
“Default” Arguments Use overloading to do “default” arguments
if client asks for 10x14 rectangle using ‘+’ draw 10x14 rectangle using ‘+’ but if client just asks for 10x14 rectangle draw 10x14 rectangle using ‘*’ Make one method your primary version usually the one with the most arguments Other methods call the primary version use “default” values for any missing arguments
55
Exercise Write the method Scams.buyLotto(int n)
prints out “You lose!” n times. Write another method Scams.buyLotto() equivalent to buying 10 lotto tickets make the body have only one line! Overload Utilities.printTitle(String) so that: can do Utilities.printTitle("Title", '='); but Utilities.printTitle("Title"); still works HINT: change original to add the underline char, then re-write the old version with a one-line body
56
One Last Convenience Printing an object doesn’t work very well!
Student s = new Student("Pat"); System.out.println(s); prints something like that’s not helpful nice if it would print name & student number maybe something like Pat (A ) meet the “toString” method
57
Using the toString method
Can ask for it… Student s = new Student("Pat"); System.out.println(s.toString()); …but don’t actually need to ask! System.out.println(s); println will actually call toString itself part of the conveniences System.out provides!
58
Creating the toString Code
NOTICE: we need to use Sopln to get the String to print toString does not print anything it only creates a String (which can then be printed) public String toString() { return name + " (" + A_NUMBER + ")"; } Student stu = new Student("Pat"); String str = stu.toString(); // creates the String "Pat (A00…)" Sopln(str); // prints Pat (A ) You are remembering to replace Sopln with System.out.println, right?
59
Add @Override Annotation
NetBeans makes a suggestion: Annotation don’t need to, but it’s encouraged @Override public String toString() { return name + " (" + A_NUMBER + ")" } we’ll explain it in CSCI 1228 or look in chapter 8 of the text – inheritance
60
Exercise A Room object has a building and a number
Room sectionARoom = new Room("Atrium", 101); Room sectionBRoom = new Room("Loyola", 179); Write a toString method for Room System.out.println("A is in " + sectionARoom + "."); System.out.println("B is in " + sectionBRoom + "."); remember: toString is called automatically remember: toString doesn’t print anything! A is in Atrium 101. B is in Loyola 179.
61
Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.