java classes
play

Java classes object-oriented programming (OOP) : Writing programs - PDF document

Objects and classes object : An entity that combines state and behavior. Java classes object-oriented programming (OOP) : Writing programs that perform most of their behavior as interactions between objects. class : 1. A


  1. Objects and classes  object : An entity that combines state and behavior. Java classes  object-oriented programming (OOP) : Writing programs that perform most of their behavior as interactions between objects.  class : 1. A program/module. or, 2. A blueprint/template for an object.  classes you may have used so far: Savitch, ch 5 String , Scanner , File  We will write classes to define new types of objects. 2 Abstraction Class = blueprint, Object = instance Music player blueprint  abstraction : A distancing between ideas and details. state : current song  Objects in Java provide abstraction: volume battery life We can use them without knowing how they work. behavior : power on/off change station/song change volume choose random song  You use abstraction every day. Example: Your portable music player. Music player #1 Music player #2 Music player #3 state: state: state:  You understand its external behavior (buttons, screen, etc.) song = ”Feels like rain" song = "Code Monkey" song = "Thriller" volume = 17 volume = 9 volume = 24  You don't understand its inner details (and you don't need to). battery life = 3.41 hrs battery life = 1.8 hrs battery life = 2.5 hrs behavior: behavior: behavior: power on/of power on/of power on/of change station/song change station/song change station/song change volume change volume change volume choose random song choose random song choose random song 4 3 How often would you expect Snake Eyes to get snake eyes? public class SnakeEyes { public static void main(String[] args){ int ROLLS = 100000; If you’re unsure on how to int count = 0; compute the probability then Die die1 = new Die(); Need to write the Die class! Die die2 = new Die(); you write a program that for (int i = 0; i < ROLLS; i++){ simulates the process. if (die1.roll() == 1 && die2.roll() == 1){ count++; } Can do this with short bit of code (google it) in a } main method, but let's say you want to reuse System.out.println(”snake eyes probability: " + (float)count / ROLLS); this code in multiple game development } projects. }

  2. Die object The Die class  The class (blueprint) knows how to create objects.  State (data) of a Die object: Die class Instance variable Description state: int numFaces numFaces the number of faces for a die int faceValue behavior: the current value produced by rolling the die faceValue roll() getFaceValue()  Behavior (methods) of a Die object: Die object #1 Die object #2 Die object #3 Method name Description state: state: state: numFaces = 6 numFaces = 6 numFaces = 10 roll the die (and return the value rolled) roll() faceValue = 2 faceValue = 5 faceValue = 8 getFaceValue() retrieve the value of the last roll behavior: behavior: behavior: roll() roll() roll() getFaceValue() getFaceValue() getFaceValue() Die die1 = new Die() ; 7 8 Die class  The following code creates a new class named Die . Object state: public class Die { instance variables public int numFaces; declared outside of any method public int faceValue; }  Save this code into a file named Die.java .  Each Die object contains two pieces of data:  an int named numFaces ,  an int named faceValue  No behavior (yet). 10 9 Instance variables Instance variables Each Die object maintains its own numFaces  instance variable : A variable inside an object that holds and faceValue variable, and thus its own part of its state. state  Each object has its own copy .  Declaring an instance variable: Die die1 = new Die(); Die die2 = new Die(); <type> <name> ; die1 numFaces 5 public class Die { 2 faceValue public int numFaces; public int faceValue; } die2 numFaces 6 3 faceValue 11

  3. Accessing instance variables Client code  Die.java can be made executable by giving it a main …  Code in other classes can access your object's  We will almost always do this…. WHY? To test the class Die before it is used by other classes  instance variables.  or can be used by other programs stored in separate .java files.  Accessing an instance variable: dot operator  client code : Code that uses a class <variable name> . <instance variable> Roll.java (client code)  Modifying an instance variable: main(String[] args) { Die die1 = new Die(); Die.java die1.numFaces = 6; <variable name> . <instance variable> = <value> ; die1.faceValue = 5; public class Die {  Examples: Die die2 = new Die(); public int numFaces; die2.numFaces = 10; public int faceValue; die2.faceValue = 3; System.out.println(”you rolled " + die.faceValue); } ... die.faceValue = 20; } 13 14 Instance methods  Classes combine state and behavior. Object behavior: methods  instance variables: define state  instance methods : define behavior for each object of a class---the way objects communicate with each other and with users.  instance method declaration, general syntax: public <type> <name> ( <parameter(s)> ) { <statement(s)> ; } 16 15 Rolling the dice: instance methods public class Die { Object initialization: public int numFaces; public int faceValue; constructors public int roll (){ faceValue = (int)(Math.random() * numFaces) + 1; return faceValue; } } Die die1 = new Die(); Think of each Die object as having its own die1.numFaces = 6; copy of the roll method, which operates int value1 = die1.roll(); on that object's state Die die2 = new Die(); die2.numFaces = 10; int value2 = die2.roll(); 18

  4. Initializing objects Die constructor public class Die {  When we create a new object, we can assign public int numFaces; Die die1 = new Die(6); public int faceValue; values to all, or some of, its instance variables: Die die1 = new Die(6); public Die (int faces) { numFaces = faces; How do we make that happen? faceValue = 1; } public int roll (){ faceValue = (int)(Math.random()*numFaces) + 1; return faceValue; } } 19 Constructors Multiple constructors are possible public class Die {  constructor : creates and initializes a new object int numFaces; Die die1 = new Die(5); int faceValue; Die die2 = new Die(); public <type> ( <parameter(s)> ) { <statement(s)> ; public Die () { } numFaces = 6;  For a constructor the <type> is the name of the class faceValue = 1;  A constructor runs when the client uses the new keyword. }  A constructor implicitly returns the newly created and initialized object. public Die (int faces) {  If a class has no constructor, Java gives it a default constructor numFaces = faces; faceValue = 1; with no parameters that sets all the object's fields to 0 or null. }  we did this in Recap.java } 21 The Student class  Let’s write a class called Student with the Encapsulation following state and behavior: Student state: String name String id int[] grades behavior: Constructor – takes id and name numGrades – returns the number of grades addGrade – adds a grade getAverage – computes the average grade 24

  5. Encapsulation Implementing encapsulation  Instance variables can be declared private to indicate  encapsulation : that no code outside their own class can access or change them. Hiding implementation details of an object from clients.  Declaring a private instance variable:  Encapsulation provides abstraction ; private <type> <name> ;  Examples: we can use objects without knowing how they work. private int faceValue; private String name; The object has:  an external view (its behavior)  Once instance variables are private, client code cannot  an internal view (the state and methods that access them: accomplish the behavior) Roll.java:11: faceValue has private access in Die System.out.println(”faceValue is " + die.faceValue); ^ 25 26 Instance variables, encapsulation and access Accessors and mutators  We provide accessor methods to examine their values:  In our previous implementation of the Die class we used the public access modifier: public int getFaceValue() { public class Die { return faceValue; public int numFaces; } public int faceValue;  This gives clients read-only access to the object's fields. }  We can encapsulate the instance variables using private:  Client code will look like this: System.out.println(”faceValue is " + die.getFaceValue()); public class Die { private int numFaces;  If required , we can also provide mutator methods: private int faceValue; } public void setFaceValue(int value) { But how does a client class now get to these? faceValue = value; } Often not needed. Do we need a mutator method in this case? 28 Benefjts of encapsulation Access Protection: Summary  Protects an object from unwanted access by clients. Access protection has three main benefits:  Example: If we write a program to manage users' bank  It allows you to enforce constraints on an object's state. accounts, we don't want a malicious client program to be able to arbitrarily change a BankAccount object's balance.  It provides a simpler client interface. Client programmers don't need to know everything that’s in the class, only the  Allows you to change the class implementation later. public parts.  As a general rule, all instance data should be modified only  It separates interface from implementation, allowing by the object, i.e. instance variables should be declared them to vary independently. private 29

Recommend


More recommend