50 likes | 68 Views
Learn about objects and classes in Java, including static and instance variables, methods, and data encapsulation. Explore how to set goals and specify handicaps for players in a game.
E N D
Lecture 5: Objects and Classes, cont’d • Continue with the Player example • Introduce GOAL as a final static variable that applies to all objects of the class • Write a second constructor that allows specifying a “handicap” for a player • Write a third that allows this to be specified as a float • Write a method that returns whether or not the player has reached the goal • etc
Static variable or instance variable? • Use a static variable (data field) when you want the variable to have the same value for all objects of the class • Access this as, for example, Player.GOAL, Math.PI • The prefix is ClassName, not an object of the class • Use CAPS when value is final (permanent) • Use an instance variable (data field) when you want the value to be different for each object in the class • Access this as, for example, jack.heads • The prefix is the specific object reference • An instance variable can also be final, for example, jack.HANDICAP
Static method or instance method? • Use a static method when it does not access or change instance variables, for example, Math.sin() • Again, prefix is the ClassName • Use an instance method when it does access or change instance variables, for example, jack.flip() • Again, prefix is the specific object reference
Objects we’ve already seen • charAt is a method of the String class: static or instance? • length is a method of the String class: static or instance • out is a variable (data field) of the System class: static or instance? • System.out is an object of the PrintStream class • println is a method of the Printstream class: static or instance? • System.out.println is a method call, using the Printstream object System.out as the prefix
Data Encapsulation • Making instance fields private, so the info can only be obtained via an accessor method, or changed by a mutator method