Created
March 29, 2013 09:54
-
-
Save joladev/5269948 to your computer and use it in GitHub Desktop.
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
// class definition | |
public class JavaClass { | |
// this is a field, also known as class variable | |
private String variableName; | |
// they can also be public, but this is not recommended! | |
public String badVariable; | |
// you can initialize the value in the same step | |
private String initalized = "HELLO"; | |
// you can choose any type you want | |
private int number = 0; | |
// you can also declare a variable as final | |
// this means that it will never ever change | |
private final int neverChange = 42; | |
// each class needs a constructor | |
// this is called when an object is made from the class | |
// if you dont write any constructor, an empty one is made for you | |
public JavaClass() { | |
// initializing code here | |
} | |
// constructors can also take parameters | |
public JavaClass(String name) { | |
variableName = name; | |
} | |
// you can have many constructors, as long as type or number of | |
// arguments set them apart | |
public JavaClass(String name, int newNumber) { | |
variableName = name; | |
number = newNumber; | |
} | |
// you'll want methods for your class | |
// a method starts with public or private | |
// followed by return type, name, parameters | |
// not that this method has retun type int and 0 paramaters | |
public int myMethod() { | |
return number; // because we have a return type, we have to return something | |
} | |
// this one takes one parameter and has return type void | |
// void means it returns nothing | |
public void thisIsVoid(String param) { | |
System.out.println(param); | |
} | |
// you will often need accessors to your fields (class variables) | |
// first, we'll make it possible to get the private variable | |
// variableName | |
public String getVariableName() { | |
return variableName; | |
} | |
// second, we'll make it possible to set the private variable | |
// variableName | |
public void setVariableName(String name) { | |
variableName = name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment