More on Objects and Classes

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Advertisements

Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Access to Names Namespaces, Scopes, Access privileges.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create.
More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.
10-Nov-15 Java Object Oriented Programming What is it?
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.
Exam tip! str.equals(), str.startsWith(), str.toUpperCase() kbd.next(), kbd.nextLine(), etc Exam tip! str.equals(), str.startsWith(), str.toUpperCase()
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
CSCI 1226 FALL 2015 MIDTERM #1 REVIEWS.  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice, keyboards,
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Review of CSCI 1226 More of What You Should Already Know.
Methods II Material from Chapters 5 & 6. Note on the Slides  We have started to learn how to write non- program Java files  classes with functions/methods,
Review of CSCI 1226 What You Should Already Know.
Data, Classes, and Objects Classes with Data Classes for Data (Chapter 5)
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter VII: Arrays.
The need for Programming Languages
Lecture 7 D&D Chapter 7 & 8 Composite Classes and enums Date.
Creating Your Own Classes
Object Oriented Programming
Chapter 2 Basic Computation
Phil Tayco Slide version 1.0 Created Sep 18, 2017
Agenda Warmup AP Exam Review: Litvin A2
Lecture 6 D&D Chapter 7 & 8 Intro to Classes and Objects Date.
Data, Classes, and Objects
Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.
Namespaces, Scopes, Access privileges
Methods.
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
CS Week 13 Jim Williams, PhD.
Data, Classes, and Objects
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
CSC 143 Inheritance.
Phil Tayco Slide version 1.0 Created Oct 2, 2017
slides created by Ethan Apter
CS1316: Representing Structure and Behavior
Outline Writing Classes Copyright © 2012 Pearson Education, Inc.
slides created by Ethan Apter
Today’s topics UML Diagramming review of terms
More Methods and Arrays
Arrays and Methods.
Namespaces, Scopes, Access privileges
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Barb Ericson Georgia Institute of Technology June 2005
Lecture 5- Classes, Objects and Methods
Object-Oriented Programming
Object Oriented Programming in java
CMSC202 Computer Science II for Majors Lecture 07 – Classes and Objects (Continued) Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
Web Design & Development Lecture 4
Review of Previous Lesson
Barb Ericson Georgia Institute of Technology Oct 2005
Just Enough Java 17-May-19.
slides created by Ethan Apter and Marty Stepp
CMPE212 – Reminders Assignment 2 due next Friday.
Visibilities and Static-ness
Review for Midterm 3.
What You Should Already Know
Classes and Methods 15-Aug-19.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

More on Objects and Classes Static Methods in Object Classes, Overloading, the toString Method Sections 6.1, 6.2, 6.4

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

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

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("A11111111", "Stu Dent", 0);

Classes and Data Data type classes designed to hold data: Student s1; Rectangle r1; s1 = new Student("A00000001", "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!

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.

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.

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

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!

Choosing Not to Change a Value Check whether the change makes sense grades must be 0..100! 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) }

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: A00123456 Name: Dent, Stu Grade: 100% Remember to replace Sopln with System.out.println!

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

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

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 (?!?)

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

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

Individual or Shared? static  shared by all objects Student stu1 stu2 A_NUMBER name grade A00000001 stu1 Dent, Stu 80 MAX_GRADE 100 A_NUMBER name grade A00000002 stu2 Tudiante, A. 85 A_NUMBER name grade A00000003 stu3 Student, Lowell E. 80

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…

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

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

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

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

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" 50..59  "D" 60..69  "C" 70..79  "B" 80..100  "A"

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

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?

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?

Programming Principles Make it impossible (or very hard) for the client to do stupid/malicious things can’t set grade outside 0..100 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

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

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…

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#

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

Assigning Student Numbers static variable belongs to class non-static variables / constants belong to objects A_NUMBER A00000001 stu1 A_NUMBER A00000002 stu2 nextANumber 1 Student 4 3 2 A_NUMBER A00000003 stu3

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

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

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

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

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

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

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

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

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

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?

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?

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)

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

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

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

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

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)

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)

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

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

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

“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

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

One Last Convenience Printing an object doesn’t work very well! Student s = new Student("Pat"); System.out.println(s); prints something like Student@1f23a that’s not helpful nice if it would print name & student number maybe something like Pat (A00000003) meet the “toString” method

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!

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 (A00000003) You are remembering to replace Sopln with System.out.println, right?

Add @Override Annotation NetBeans makes a suggestion: add @Override 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

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.

Questions?