Download presentation
Presentation is loading. Please wait.
1
Data, Classes, and Objects
Classes with Data Classes for Data (Chapter 5)
2
Outline Review of methods Introduction to objects
helper class in a project Introduction to objects Creating our own object classes instance variables constructors getters setters instance constants
3
Calling a Method You ask some thing to do it
ask System.out to print stuff ask Math to calculate stuff ask a Scanner to read stuff ask a String about itself Address yourself to the thing System.out.println("3^5 is " + Math.pow(3, 5)); put a dot after the name of the thing
4
What is this “Thing”? Can be a class … or an object…
its name starts with a big letter Math.pow(5, 18.2) … or an object… its name starts with a little letter kbd.nextInt(); answer.equalsIgnoreCase("Yes"); And then there’s System.out an object named out that belongs to the class named System
5
“Helperˮ Class Can have more than one class in a package
Can call methods from the other classes if the methods are declared public Just like any other method call A03Helper.printTaxBrackets(); method is in class A03Helper method is named printTaxBrackets class A03Helper must be in same package package a03, for example
6
Note on the Slides All of our classes have been programs so far
now we start to write non-program classes In order to use them, we need a program… program asks non-program to do things …so we need two (or more) files program class code will be in dark blue non-program class code will be in dark orange
7
Program and Non-Program
TaxCollector public class TaxCollector { public static void main(String[] args) { … if (userSaysYes("See tax table?")) { A03Helper.printTaxBrackets(); } A03Helper public class A03Helper { public static void printTaxBrackets() { …. } …
8
Program vs. Non-Program
Program classes have a main method you can run these files Non-Program classes have no main method you cannot run these files selecting “Run File…ˮ command gives an error that’s what it’s supposed to do!
9
Classes vs. Objects Classes can be used right away
Utilities.printTitle("Utilities Demo"); so long as we can “see” them Objects need to be created except for Strings, which are so massively useful… Scanner kbd = new Scanner(System.in); objects contain data different objects have different data methods are mostly about that data
10
String Objects and Data
Strings String firstName = "Mark"; String lastName = "Young"; methods deal with data in the String S.o.pln(firstName.length()); // prints 4 S.o.pln(lastName.length()); // prints 5 S.o.pln(firstName.toUpperCase()); // prints MARK S.o.pln(lastName.toLowerCase()); // prints young
11
Scanner Objects and Data
Scanners have data, too where they’re getting their data from Scanner kbd = new Scanner(System.in); kbd gets it from System.in (the keyboard) String line = kbd.nextLine(); // next line from System.in Scanner str = new Scanner(" "); str gets it from the String “ ” int n1 = str.nextInt(); // n1 is set to 10 int n2 = str.nextInt(); // n2 is set to 20 int n3 = kbd.nextInt(); // n3 is set to next int from the user
12
Object Oriented Programming
Programming arranged around objects main program creates the objects objects hold the data objects call each others’ methods objects interact to achieve program goal Very important in GUI programs Graphical User Interface WIMP (Windows, Icons, Menus, Pointers) interface
13
What are Objects? An object in a program often represents a real-world object… an animal, a vehicle, a person, a university, … …or some abstract object… a colour, a shape, a species, … …or some thing the program needs to track a string, a window, a GUI button, …
14
Object Classes What kind of object it is
its data type is a Class String s1, s2; // s1 & s2 are Strings Scanner kbd, str; // kbd & str are Scanners Animal rover, hammy; // rover & hammy are Animals Color c1, c2; // c1 & c2 are Colors JButton okButton, cancelButton; // … are JButtons Objects in the same class do the same kinds of things To use Color & Button, you need to import java.awt.Color; import javax.swing.JButton;
15
Declaring Objects Most Java objects created using new
usually with arguments arguments depend on the class kbd = new Scanner(System.in); rover = new Animal(Animal.DOG); // I made this up! c1 = new Color(255, 127, 0); // This is orange okButton = new JButton("OK"); not Strings, tho’ s1 = "Strings are special!"; s2 = new String("But this works, too!"); Remember to import java.awt.Color; import javax.swing.JButton;
16
Object Data Methods access pieces of object data
s1.length() is 20; s1.charAt(0) is 'S' Each object has its own data: s1’s characters not the same as s2’s might be the same (by coincidence) s1 and s2 same length s1 characters length Strings are special! 20 s2 characters length But this works, too! 20
17
Object Data Each kind of object has its own kind of data
Color has red, green, blue and alpha data orange has 255 R, 127 G, and 0 B (and 255 A) c1.getRed() returns 255; c1.getGreen() returns 127 c2.getRed() returns 17; c2.getBlue() returns 251 c1 red green blue alpha 255 127 c2 red green blue alpha 17 179 251 255
18
A Student Class A class for holding student information
student number name home address grades ... We’ll start simple: number, name, one grade (in percent) these are called “properties” of the Student stu number name pctGrade A “Dent, Stu” 81
19
Creating Data Class in NetBeans
Create the project as usual Java application, naming the program Create a Java class NOT a Java main class! Open file and look inside class definition it should be empty (no main method) public class Student { }
20
Student Data Student class needs variables to hold the data for each student number is String(!), name is String, grade is int These variables called “instance variables” each Student object an instance of Student class each Student object has its own variables Stu Dent’s A# and grade different from A. Tudiant’s
21
Student Class (Start) public class Student { private String aNumber; // A00... private String name; // family name, givens private int pctGrade; // … } instance variables are declared private (not public) no “static”; no “final” methods will be declared below
22
Public vs. Private Public = anyone can use these
Public name anyone can change my name Public grade anyone can change my grade Public method anyone can use this method Private = only I can use them Private name only I can change my name Private grade only I can change my grade Anyone can ask, but I get a veto Actually, any Student can change my name/grade; other classes have to ask
23
Static vs. Non-Static Static = shared with all others of my kind
Static name all students have the same name Static grade all students have the same grade Static method all students give same answer Non-Static = each object has its own Non-static name each student has own name Non-static grade each student has own grade
24
Declaring a Student Give A#, name and grade when create
Student s1, s2; s1 = new Student("A ", "Dent, Stu", 81); s2 = new Student("A ", "Tudiaunt, A.", 78); or can combine the steps: Student s3 = new Student("A ", "No, Dan", 0); arguments are String (aNumber), String (name), and int (percent grade)
25
Student Constructor Constructor “builds” the Student object
gives a value to each of the instance variables private String aNumber; // A00… private String name; // Last, First private int grade; // public Student(String a, String n, int g) { aNumber = a; name = n; grade = g; } a, n, and g are the parameters: the values the caller wants to use; aNumber, name, and grade are the instance variables: the values we will use.
26
Constructors Generally declared public
anyone can build a Scanner, a Student, … Name is exactly the same as the class name class Student constructor named “Student” class Animal constructor named “Animal” No return type not even void! Argument for each instance variable (often)
27
Constructors Their job is to give a value to each instance variable in the class and so often just a list of assignment commands instanceVariable = parameter; aNumber = a; name = n; grade = g; But may want to check if values make sense so maybe a list of if-else controls
28
Checking Values If given value makes no sense, use a default
but still instanceVariable = (something); public Student(String a, String n, int g) { if (a.startsWith("A") && a.length() == 9) { aNumber = a; } else { aNumber = "(illegal)"; } name = n; …
29
Exercise Add code to the constructor so that grades less than 0 are set to 0, grades over 100 are set to 100, and other grades are accepted.
30
So Now We’ve Saved this Info…
We want to be able to ask about it maybe even change it But the instance variables are private can’t change them directly: Student stu = new Student("A ", "Dent, Stu", 100); stu.name = "Dummikins, Dummy"; can’t even ask about them! System.out.println(stu.aNumber); name is private in Student! aNumber is private in Student!
31
Methods to Get Information
“Getters” usually named get + name of instance variable but capitalized in camelCase System.out.println(stu.getName()); returns stu’s name System.out.println(stu.getANumber()); returns stu’s A number System.out.println(stu.getPctGrade()); returns stu’s percentage grade
32
Student “Getters” These getters are very simple!
just return the instance variable method return type same as type of variable private String aNumber; // A00… private String name; // Last, First public String getName() { return name; } public String getANumber() { return aNumber; public! Anyone can ask! No static! Each student has own name!
33
Exercise Write the getter for the percent grade recall:
private int grade; //
34
Sample Client Code Student record tester reads & prints student records until user types Q Scanner kbd = new Scanner(System.in); Student stu; String num, name; int pct; System.out.print("Enter student’s A-# (or Q to quit): "); num = kbd.nextLine(); ...
35
Sample Client Code (continued)
while (!num.startsWith("Q")) { // read student info System.out.print("Enter student name: "); name = kbd.nextLine(); System.out.print("Enter percent grade: "); pct = kbd.nextInt(); kbd.nextLine(); // create and print student information stu = new Student(num, name, pct); System.out.println("\n" + stu.getANumber() + " (" + stu.getName() + ") got " + stu.getPctGrade() + "%"); // get next student’s number System.out.print("Enter student’s A-# (or Q to quit): "); num = kbd.nextLine(); }
36
More Student Methods Maybe a (void) method to print out all info
stu.printStudentRecord(); public void printStudentRecord() { System.out.println("Number: " + aNumber); System.out.println("Name: " + name); System.out.println("Grade: " + pctGrade); } Number: A Name: Dent, Stu Grade: 100%
37
Sample Client Code (revised)
while (!num.startsWith("Q")) { // read student info System.out.print("Enter student name: "); name = kbd.nextLine(); System.out.print("Enter percent grade: "); pct = kbd.nextInt(); kbd.nextLine(); // create and print student information stu = new Student(num, name, pct); stu.printStudentRecord(); // get next student’s number System.out.print("Enter student’s A-# (or Q to quit): "); num = kbd.nextLine(); }
38
Methods to Change Information
Some fields may need to be changed name and grade, for example student number should NOT be changed! Need a method to do that, too! stu.name = "Dummikins, Dummy"; Methods called “setters” named “set” + name of instance variable stu.setName("Dummikins, Dummy"); stu.setPctGrade( ); name is private in Student!
39
Setters Given the new value the caller wants
normally we will use that value public void setName(String newName) { name = newName; } but we might want to reject it public void setPctGrade(int newGrade) { if (0 <= grade && grade <= 100) { pctGrade = newGrade; May want to print an error message…
40
Another Useful Setter A method to set both changeable values
public void setStudent(String newName, int newGrade) { setName(newName); setPctGrade(newGrade); } sample call: stu.setStudent("Dent, Stuart", 95); Use the other setters – they will make sure that the values are appropriate!
41
Warning Don’t use program variables in Student
public void setStudent(String newName, int newGrade) { stu.setName(newName); stu.setPctGrade(newGrade); } even tho’ method called with stu stu.setStudent("Dent, Stuart", 95); stu is a variable in a program method setStudent is an entirely different method it doesn’t know other methods’ variables cannot find symbol: stu
42
Warning Also can’t use name of class
public void setStudent(String newName, int newGrade) { Student.setName(newName); Student.setPctGrade(newGrade); } even tho’ this method is in the class Student not every student has the same name Java won’t let you change all their names at once only static methods can use class name! non-static method cannot be referenced from static context
43
this Object There is a word for the name of this object
the object that got asked to do something the name is this public void setStudent(String newName, int newGrade) { this.setName(newName); this.setPctGrade(newGrade); } stu.setStudent("Dent, Stuart", 95); here this Student is stu will be other Students at other times
44
What is “this”? Recall how we change name and grade:
stu.set("Dent, Stuart", 100); goes to set method in Student class public void set(String n, int g) { ... } need to call setName and setPctGrade stu.setName(n); stu.setPctGrade(g); stu is only available in main! Student class never heard of him! “this” means “whichever variable was used” in this case, it’ll mean stu unknown symbol: variable stu
45
Using “this” Refers to whatever object was called
s1.set("Name, New", 100); // sets s1’s name & grade this.setName s1.setName and s1.setPctGrade s2.set("Name, New", 75); // sets s2’s name and grade this.setName s2.setName and s2.setPctGrade Can’t be used in main this.set("Work, Dozen", 0); nor in other static methods e.g. methods in class A03Helper non-static variable cannot be referenced from a static context
46
Last Changes NetBeans says that aNumber can be final
it can, and it should (it shouldn’t ever change) private final String aNumber; should restyle the name to constant style select aNumber, right click, Refactor > Rename... change name to A_NUMBER check “apply rename on comments” click Refactor private final String A_NUMBER; all references to it also changed!
47
Make A_NUMBER public If it’s final, no one can change it
not even my methods! A_NUMBER = "A "; so we don’t need to make it private! public final String A_NUMBER; Now don’t need a getter client can just use the public instance constant System.out.println(stu.A_NUMBER); but it’s still OK to have it! cannot assign to final variable NOTE: the constructor actually does that! But it’s OK, because it’s not changing the value!
48
Exercise Create a Car class make, model, year and colour
what methods do we want/need? which properties can change, for example? marksCar year make model colour 2009 “Toyota” “Corolla” “red”
49
Questions
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.