1.76k likes | 1.91k Views
Classes. Chapter 6 Spring 2007 CS 101 Aaron Bloomfield. The Car class. More on classes vs. objects. A new example: creating a Car class. What properties does a car have in the real world? Color Position (x,y) Fuel in tank We will implement these properties in our Car class
E N D
Classes Chapter 6 Spring 2007 CS 101 Aaron Bloomfield
A new example: creating a Car class • What properties does a car have in the real world? • Color • Position (x,y) • Fuel in tank • We will implement these properties in our Car class public class Car { private Color color; private int xpos; private int ypos; private int fuel; //... }
Car - color - xpos - fuel - ypos + … Car’s instance variables public class Car { private Color color; private int xpos; private int ypos; private int fuel; //... }
Car - color = null - xpos = 0 - fuel = 0 - ypos = 0 + … Instance variables and attributes • Default initialization • If the variable is within a method, Java does NOT initialize it • If the variable is within a class, Java initializes it as follows: • Numeric instance variables initialized to 0 • Logical instance variables initialized to false • Object instance variables initialized to null
Car behaviors or methods • What can a car do? And what can you do to a car? • Move it • Change it’s x and y positions • Change it’s color • Fill it up with fuel • For our computer simulation, what else do we want the Car class to do? • Create a new Car • Plot itself on the screen • Each of these behaviors will be written as a method
Creating a new car • To create a new Car, we call: • Car c = new Car(); • Notice this looks like a method • You are calling a special method called a constructor • A constructor is used to create (or construct) an object • It sets the instance variables to initial values • The constructor: public Car() { fuel = 1000; color = Color.BLUE; }
Constructors public Car() { fuel = 1000; color = Color.BLUE; } No return type! EXACT same name as class For now, all constructors are public
Our Car class so far public class Car { private Color color; private int xpos; private int ypos; private int fuel; public Car() { fuel = 1000; color = Color.BLUE; } } public class Car { private Color color = Color.BLUE; private int xpos; private int ypos; private int fuel = 1000; public Car() { } }
Car - color = Color.BLUE - xpos = 0 - fuel = 1000 - ypos = 0 + Car() + … Our Car class so far public class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000; public Car() { } } • Called the default constructor • The default constructor has no parameters • If you don’t include one, Java will SOMETIMES put one there automatically
Alien Song • AlienSong.mpg
Another constructor • Another constructor: public Car (Color c, int x, int y, int f) { color = c; xpos = x; ypos = y; fuel = f; } • This constructor takes in four parameters • The instance variables in the object are set to those parameters • This is called a specific constructor • An constructor you provide that takes in parameters is called a specific constructor
Car - color = Color.BLUE - xpos = 0 - fuel = 1000 - ypos = 0 + Car() + Car (Color, int, int, int) + … Our Car class so far public class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000; public Car() { } public Car (Color c, int x, int y, int f) { color = c; xpos = x; ypos = y; fuel = f; } }
c1 c2 Car Car - color = Color.BLUE - color = Color.BLACK - xpos = 0 - xpos = 1 - fuel = 1000 - fuel = 500 - ypos = 0 - ypos = 2 + Car() + Car (Color, int, int, int) + … + Car() + Car (Color, int, int, int) + … Using our Car class • Now we can use both our constructors: Car c1 = new Car(); Car c2 = new Car (Color.BLACK, 1, 2, 500);
So what does private mean? Note that it’s a different class! • Consider the following code public class CarSimulation { public static void main (String[] args) { Car c = new Car(); System.out.println (c.fuel); } } • Recall that fuel is a private instance variable in the Car class • Private means that code outside the class CANNOT access the variable • For either reading or writing • Java will not compile the above code • If fuel were public, the above code would work
So how do we get the fuel of a Car? • Via accessor methods in the Car class: public int getFuel() { return fuel; } public Color getColor() { return color; } • As these methods are within the Car class, they can read the private instance variables • As the methods are public, anybody can call them • public int getYPos() { • return ypos; • } • public int getXPos() { • return xpos; • }
So how do we set the fuel of a Car? • Via mutator methods in the Car class: public void setFuel (int f) { fuel = f; } public void setColor (Color c) { color = c; } • As these methods are within the Car class, they can read the private instance variables • As the methods are public, anybody can call them public void setXPos (int x) { xpos = x; } public void setYPos (int y) { ypos = y; }
Car - color = Color.BLUE - xpos = 0 - fuel = 1000 - ypos = 0 + Car() + Car (Color, int, int, int) +void setXPos (int x) +void setYPos (int y) +void setColor (Color c) +void setFuel (int f) +int getFuel() +int getXPos() +int getYPos() +Color getColor() + … Why use all this? • These methods are called a get/set pair • Used with private variables • We’ll see why one uses these later in this slide set • Our Car so far:
Back to our specific constructor public class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000; public Car (Color c, int x, int y, int f) { color = c; xpos = x; ypos = y; fuel = f; } } public class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000; public Car (Color c, int x, int y, int f) { setColor (c); setXPos (x); setYPos (y); setFuel (f); } }
Back to our specific constructor • Using the mutator methods (i.e. the ‘set’ methods) is the preferred way to modify instance variables in a constructor • We’ll see why later
So what’s left to add to our Car class? • What else we should add: • A mutator that sets both the x and y positions at the same time • A means to “use” the Car’s fuel • A method to paint itself on the screen • Let’s do the first: public void setPos (int x, int y) { setXPos (x); setYPos (y); } • Notice that it calls the mutator methods
Using the Car’s fuel • Whenever the Car moves, it should burn some of the fuel • For each pixel it moves, it uses one unit of fuel • We could make this more realistic, but this is simpler • Math.abs() returns the absolute value public void setXPos (int x) { xpos = x; } public void setYPos (int y) { ypos = y; } public void setXPos (int x) { fuel -= Math.abs (getXPos()-x); xpos = x; } public void setYPos (int y) { fuel -= Math.abs (getYPos()-y); ypos = y; }
Setting both positions at once public void setPos (int x, int y) { setXPos(x); setYPos(y); } • Notice that to modify the instance variables, the mutator methods are used
Drawing the Car • The simple way to have the Car draw itself: public void paint (Graphics g) { g.setColor (color); g.fillRect (xpos-50, ypos-100, 100, 200); } • This draws a single rectangle that is 100 by 200 pixels in size • Lets use constants for the car’s height and width...
Drawing the Car • A better version: private final int CAR_WIDTH = 100; private final int CAR_HEIGHT = 200; public void paint (Graphics g) { g.setColor (color); g.fillRect (getXPos()-CAR_WIDTH/2, getYPos()-CAR_HEIGHT/2, CAR_WIDTH, CAR_HEIGHT); } • This makes it easier to change the car size • We could have made the car size instance variables and set them via mutators • Lets add tires!
Drawing the Car private final int CAR_WIDTH = 100; private final int CAR_HEIGHT = 200; private final int TIRE_WIDTH = 20; private final int TIRE_HEIGHT = 40; private final int TIRE_OFFSET = 20; public void paint (Graphics g) { g.setColor (color); g.fillRect (getXPos()-CAR_WIDTH/2, getYPos()-CAR_HEIGHT/2, CAR_WIDTH, CAR_HEIGHT); // Draw the tires g.setColor (Color.BLACK); g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH), getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH), getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()+(CAR_WIDTH/2), getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()+(CAR_WIDTH/2), getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT); } Don’t worry about this – just know that it draws four tires
What happens when the car runs out of fuel? • We could do a number of things: • Not allow the car to move anymore • Print out a message saying, “fill me up!” • We’ll color the car red • We’ll insert the following code at the beginning of the paint() method: if ( fuel < 0 ) { color = Color.RED; }
Drawing the Car private final int CAR_WIDTH = 100; private final int CAR_HEIGHT = 200; private final int TIRE_WIDTH = 20; private final int TIRE_HEIGHT = 40; private final int TIRE_OFFSET = 20; public void paint (Graphics g) { if ( fuel < 0 ) { color = Color.RED; } g.setColor (color); g.fillRect (getXPos()-CAR_WIDTH/2, getYPos()-CAR_HEIGHT/2, CAR_WIDTH, CAR_HEIGHT); // Draw the tires g.setColor (Color.BLACK); g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH), getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH), getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()+(CAR_WIDTH/2), getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()+(CAR_WIDTH/2), getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT); }
Our car in action • CarGUI.java
How well do you feel you understand the Car class? • Very well! This stuff is easy! • Fairly well – with a little review, I’ll be good • Okay. It’s not great, but it’s not horrible, either • Not well. I’m kinda confused • Not at all. I’m soooooo lost.
Cubic Tragedy • Cubic_tragedy_m640.mov
What I’m not expecting you to know yet… • What the static keyword means • And why the main() method is • And why other methods are not • Why you should always call the mutator methods, instead of setting the field directly • Just know that it’s a good programming practice, and follow it • We’ll see why later • Why instance variables are supposed to be private • Just know that it’s a good programming practice, and follow it • Again, we’ll see why soon
Terminology • An attribute of a class can be called: • Instance variable or class variable • We’ll see the difference later • Static variable (or static field) • Synonymous with class variable • Field • Generally means either type • Variable • Also means either type • Attribute • Property • Argh! • I will generally use the terms variable or field when I am not differentiating between the two • And instance variable/field and class variable/field when I am
The main() method • Consider a class with many methods: public class WhereToStart { public static void foo (int x) { // ... } public static void bar () { // ... } public static void main (String[] args) { // ... } } • Where does Java start executing the program? • Always at the beginning of the main() method!
Running a class without a main() method • Consider the Car class • It had no main() method! • The main() method was in the CarSimulation (or CarGUI) class • So let’s try running it…
Program Demo • Car.java
Variable initialization • A local variable is NOT initialized to a default value • This is any variable declared within a method • Or within a block within a method • This is pretty stupid, in my opinion • Parameters are initialized to whatever value they are passed • Instance and class variables are initialized to default values • Numbers to zero, booleans to false, references to null • This means any field in a class • Either class variables or instance variables
How well do you feel you understand creating classes so far? • Very well! This stuff is easy! • Fairly well – with a little review, I’ll be good • Okay. It’s not great, but it’s not horrible, either • Not well. I’m kinda confused • Not at all. I’m soooooo lost.
The Circle class Introducing static-ness, visibilities, etc.
A Circle class • We are going to develop a Circle class • Perhaps for use in a graphics program • Why? • Partly to review creating classes • Go over some topics that were a bit fuzzy • Constructors and creating objects • Show why one uses the get/set methods instead of directly modifying the instance variables • Discuss visibilities (public, private, etc.) • Discuss the static keyword
Circle class properties • What properties does a circle have? • Radius • PI = 3.141592653589793234 • Color (if plotting in a graphics program) • (x,y) location • These properties will become instance variables • We are only going to play with the first two (radius and PI) in this example • Thus, we are ignoring the color and location
c Circle • radius = 0.0 • - PI = 3.14159… • - … + … Our Circle class Circle c = new Circle(); public class Circle { double radius; double PI = 3.1415926536; } Note the radius field is not initialized by us Note the fields are not static We’re ignoring the public for now
c Circle • radius = 0.0 • - PI = 3.14159… • - … + … Accessing our Circle object • Any variable or method in an object can be accessed by using a period • The period means ‘follow the reference’ • Example: System.in • Example: System.out.println (c.radius); • Example: c.PI = 4; This is bad – PI should have been declared final (this will be done later)
What’s the output? public class Circle { double radius; double PI = 3.1415926536; } public class CircleTest { public static void main (String[] args) { int x; Circle c = new Circle(); System.out.println (x); } } • When a variable is declared as part of a method, Java does not initialize it to a default value Java will give a “variable not initialized” error
What’s the output now? public class Circle { double radius; double PI = 3.1415926536; } public class CircleTest { public static void main (String[] args) { int x; Circle c = new Circle(); System.out.println (c.radius); } } • When a variable is declared as part of a class, Java does initialize it to a default value Java outputs 0.0!
What’s going on? • A (method) variable needs to be initialized before it is used • Usually called a local variable • A instance variable is automatically initialized by Java • All numbers are initialized to 0, booleans to false, etc. • This is a bit counter-intuitive…
Circle class behaviors • What do we want to do with (and to) our Circle class? • Create circles • Modify circles (mutators) • Find out about our circles’ properties (accessors) • Find the area of the circle • Plot it on the screen (or printer) • A few others… • These will be implemented as methods