Created
September 27, 2011 02:40
-
-
Save bittersweetryan/1244178 to your computer and use it in GitHub Desktop.
Class with instance variables and constructors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Car{ | |
/* these are instance variables, they are defined outside of any function which means that any | |
function in the class can access them. Since they are private ONLY functions in the class | |
can access them. However note that the String is not set to anything, trying to access it | |
would throw an error. | |
*/ | |
private String color; | |
private int doors; | |
//this is a default constructor, it has no arguments | |
public Car(){ | |
//now we set the car variable to something generic now its instantiated and we can access it | |
this.color = ""; | |
} | |
//this is a full constructor, both of the class variables are passed in | |
public Car(String color, int doors){ | |
//we use the this keyword to refer to the class variable, the color on the right | |
//side is the value of the arguments | |
this.color = color; | |
this.doors = doors; | |
} | |
/* these are called getters and setters, or accessors and mutators | |
they are public methods to get and set the class variables. the reason | |
is that we can check the values when setting or getting */ | |
public String getColor(){ | |
return this.color; | |
} | |
public void setColor(String color){ | |
//lets say we dont like yellow cars we can ignore yello cars | |
if(!color.equals("yellow")){ | |
this.color = color; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment