Download presentation
Presentation is loading. Please wait.
1
Lecture 3
2
Public and Private As your programs get more complex, you will lose track of the details of the parts you are not currently working on In your advanced programming classes, you will collaborate with other programmers who may not solve problems in the same way you would Professional software applications may contain code written by hundreds or even thousands of programmers working for many different employers. More than 10,000 programmers have worked on the Linux kernel. All software contains errors, and some also contains intentionally malicious code. 2 2
3
Public and Private Public data may be accessed directly by any object that has a reference to the current object This means that any other object can change your data in any way that seems appropriate to whoever wrote it This leads to unpredictable behavior, because programmers are almost as crazy as users Private fields and methods may only be used from within the current object and other objects of the same class Most classes have private data which can be accessed or changed only by using public methods The public methods are part of the object and thus can see or change the private data 3 3
4
Public and Private We can reduce the confusion by providing well-defined interfaces instead of allowing other objects to access our data directly To use an object of a certain class, you only need to know its public methods. You can protect the data in your own classes by allowing it to be changed or accessed only by methods you wrote and chose to make publicly available This principle is called information hiding or encapsulation 4 4
5
Public and Private The sport of American football includes several ways to score points. The main ones are these: A touchdown scores 6 points A conversion, also called an extra point, scores one point but can only be scored immediately after a touchdown A safety scores 2 points A field goal scores 3 points Note that there is no way to score four, five, seven, etc. points at once 5 5
6
Public and Private public class FootballScore {
// models the score for one team in a game of American Football private int score; public int getScore() { return score; } public void touchdown() { score += 6; public void extraPoint() { score += 1; public void safety() { score += 2; public void fieldGoal() { score += 3; 6 6
7
Public and Private How the private data / public methods architecture benefits FootballScore: If external objects (say, a FootballGame object) could arbitrarily change the score in FootballScore, buggy or malicious code could interfere with the functioning of the class for example, by adding 5 to the score or dividing it by 2, changes that are invalid in American Football. this kind of problem is hard to find and extremely hard to fix, since the bad code was probably written by someone else In FootballScore, the available ways to change the score are limited to the ways points can actually be scored in Football If anything else needs to be done when the score changes, like updateScoreboard(); or notifyBookmaker(); the author of FootballScore can take responsibility for making sure the public methods trigger it 7 7
8
Public and Private How the private data / public methods architecture benefits objects that use FootballScore: Other objects do not have to understand the internal functioning of FootballScore They only need to know that they can find out the score by calling getScore() and can deal with scoring events by calling, for example, touchdown(). If you decide to change the design of FootballScore, nothing in any other class needs to change as long as the public interface remains the same. This will become very important as your classes get more sophisticated. Suppose you write a class with a method that determines whether or not a touchdown was actually scored. You may sometimes need to change the algorithm used by the method (eg, to use new electronic sensors or to accommodate rule changes in the sport.) As long as the method signature remains the same, other objects don't need to understand anything about it or even know when you change it. 8 8
9
Package Private The default visibility is package private
Package private data and methods are visible to any object of a class defined in the package This is rarely what you actually want 9 9
10
Private Methods Private methods may be used only by the object itself:
public class VanGogh{ int ears; private void chop(){ ears -= 1; } 10 10
11
Accessors and Mutators
Methods like getScore() are called “Accessors” because they provide access to the data. These are informally called “getters.” Methods like touchdown() are called “Mutators” because they change data. These are also informally called “setters.” 11 11
12
This The keyword this is a reference to the current object.
It has many uses; one is for the case that a setter has a parameter with the same name as the field in the class. private int heightInCm; public void setHeightInCm(int heightInCm){ this.heightInCm = heightInCm; } You need to understand this usage, but you don't have to like it. You can just use a different name for the parameter in the method signature: public void setHeightInCm(int heightInCmIn){ heightInCm = heightInCmIn; 12 12
13
main() As you know, the JVM executes the application by invoking (running) the main() method, which may then call other methods So far, all your classes have contained main() methods We will soon begin writing programs that contain more than one class. In your CS202 programs, only one class per program will need a main(). The example used for constructors above contained three classes, of which one contained a main(). Here is another example. 13 13
14
Menu with Loop and Switch
It is very common for an application to provide a menu of options within a loop that continues until the user chooses to quit: public class MenuLoopDemo { public static void main(String[] args){ int choice = 0; String[] options = {"Quit", "EasyA", "Swift Kick"}; do{ choice = JOptionPane.showOptionDialog(null, "Choose One", "Please Select One", 2, choice, null, options, options); switch(choice){ case 1: easyA(); break; case 2: swiftKick(); } } while(choice != 0); public static void easyA(){ JOptionPane.showMessageDialog(null, "Easy A!"); public static void swiftKick(){ JOptionPane.showMessageDialog(null, "Swift Kick!"); } 14 14
15
Driver class Your classes that model real world entities or logical parts of your application should not contain test data. In most cases, they should not contain main() methods. A driver is a class that is intended to be used to test or demonstrate the functionality of other classes. It contains a main() that creates instances of other classes and runs their public methods. For example, if we are developing a Book class, we might write a driver that instantiates some Books, gives them ISBNs, titles, etc., and runs whatever public methods they have. 15 15
16
Driver class private String name; public void sayName() { 16
package demos; public class Monster { private String name; public Monster(String nameIn) { name = nameIn; } public void sayName() { System.out.println("Hi, my name is " + name); 16 16
17
Driver classes package demos; public class MonsterDriver {
public static void main(String[] args){ Monster m1 = new Monster("Godzilla"); Monster m2 = new Monster("Mothra"); m1.sayName(); m2.sayName(); } 17 17
18
Multi-class application
This class will be used as a data type in an application. Notice that there is no main() method. This class has only the implicit constructor, so the data fields initially have default values (0.0 for the double) name and grade are called “instance variables” because there is one name and one grade for each object of the class Student, that is, for each instance of Student. package demos; public class Student { private String name; private double grade; public String getName() { return name; } public double getGrade() { return grade; public void setName(String nameIn) { name = nameIn; public void setGrade(double gradeIn) { grade = gradeIn; 18 18
19
Multi-class application
/* GradeBook and Student are in the same package. If they were in different packages, we would need an import */ package demos; public class GradeBook { public static void main(String[] args) { // create an array of Students Student[] students = new Student[4]; // create Students and put them in the array for(int counter = 0; counter < students.length; counter++) students[counter] = new Student(); // supply data for the Students students[0].setName("Fred"); students[0].setGrade(82.0); students[1].setName("Wilma"); students[1].setGrade(86.5); students[2].setName("Barney"); students[2].setGrade(63.0); students[3].setName("Betty"); students[3].setGrade(96.5); // output the data for(Student s: students) System.out.println(s.getName() + ": " + s.getGrade()); } 19 19
20
Compiling Multi-Class Apps
When you compile the first class in an app from the command line, it will compile all classes it can find in a chain of references If class a refers to class b, but b does not have a reference to a, it is easier for you to compile a first. If you compile using an IDE, you don't have to worry about this. 20 20
21
Trace Code animation Declare myCircle
Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle no value 21
22
Trace Code, cont. animation Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle no value Create a circle 22
23
Assign object reference to myCircle
animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value Assign object reference to myCircle 23
24
Trace Code, cont. Declare yourCircle animation
Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle no value Declare yourCircle 24
25
Create a new Circle object
animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle no value Create a new Circle object 25
26
Assign object reference to yourCircle
animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle reference value Assign object reference to yourCircle 26
27
Change radius in yourCircle
animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle reference value Change radius in yourCircle 27
28
Differences between Variables of Primitive Data Types and Object Types
28
29
Copying Variables of Primitive Data Types and Object Types
29
30
Passing Objects to Methods
Passing by value for primitive type value (the value is passed to the parameter) Passing by value for reference type value (the value is the reference to the object) 30
31
Passing Objects to Methods, cont.
31
32
Array of Objects Circle[] circleArray = new Circle[10]; An array of objects is actually an array of reference variables. So invoking circleArray[1].getArea() involves two levels of referencing as shown in the next figure. circleArray references to the entire array. circleArray[1] references to a Circle object. 32
33
Array of Objects, cont. Circle[] circleArray = new Circle[10]; 33
34
toString() Consider this code (Student must also be in the package or be imported): public class Demo { public static void main(String args[]) { Student joe = new Student(); joe.setName("Joe"); joe.setGrade(100.0); System.out.println(joe); } // end main() } The output will look approximately like this: We have not printed out the useful information in the object, just the name of the class and the hash code (a value used internally by the compiler and JVM for various purposes) of the object! 34 34
35
toString() There is a built-in toString() method that shows the name of the class and the hash code of the object. This is what we got in the last example. If you want to provide a more useful String representation of objects, write a toString() method in the class. toString() is public, takes no parameters, and returns a String, so its method header is public String toString() We might add a toString() like this to Student: public String toString(){ return "Name: " + name + "; Grade: " + grade; } If we now run the same code from Gradebook, we get this output: Name: Joe; Grade: 100.0 35 35
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.