1 / 5

Understanding Objects and Classes in Java

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.

hornbeck
Download Presentation

Understanding Objects and Classes in Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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

  3. 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

  4. 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

  5. Data Encapsulation • Making instance fields private, so the info can only be obtained via an accessor method, or changed by a mutator method

More Related