120 likes | 301 Views
AP Computer Science. The Logic of Classes. A Class is a Blueprint. A Class tells us what type of object we can create. So for example: If I write a class called Monster, it will determine what properties any monster I might create will have. the Monster Class - Fields.
E N D
AP Computer Science The Logic of Classes
A Class is a Blueprint A Class tells us what type of object we can create. So for example: If I write a class called Monster, it will determine what properties any monster I might create will have.
the Monster Class - Fields My monster class will have several values - we will call these fields. size strength soolness speed color
Default values for fields Whenever a new monster is created, these fields need to have values. So let us set some default values: size = 90; strength = 50; speed = 12; coolness = 80; color = "Red"; This means that whenever a Monster is created it will have those values in its fields
Creating Monster Objects Creating Monster Objects is rather simple: We use the following lines of code to create two Monster objects : Monster Sparky = new Monster(); Monster Junior= new Monster(); Of course these two Monsters are identical- they both have a strength field with a value 50, a color of "red", etc.
Changing the values in Monster object fields If we wanted to access the Junior's color field we would use the following expression: Jumior.color Of course to get Sparky's strength we would use Sparky.strength to change these values we just do the following: Junior.color= "blue"; or Sparky.strength= 55;
Examples and Practice Consider the following sequence of commands: Monster Godzilla = new Monster(); Godzilla.coolness = 76; If (Godzilla.strength > 20) Godzilla.coolness = 86; What is Godzilla.strength after the above lines execute? Write the commands that will create three Monster objects. You may choose the names, but one must have a strength of 23, a coolness of 45, and a color of “purple”; the others can be however you like, but you must change at least two fields from the default values.
Tips Before you have any objects, you have no fields! A class is a blueprint for objects! In csc terms, Godzilla was an “instance” of a Monster object.
/** Java Code representing the class described in the first PowerPoint. June 2014 */ public class Monster { public int strength; public int size; public int speed; public int coolness; public String color; /** * Constructor for objects of class ObjectLogic1 note this class has only fields, * no methods besides the constructor */ public Monster() { strength = 50; size = 90; speed = 12; coolness = 80; String color = new String(); color = "Red"; } }