A class is something that encapsulates functions as well as data, e.g.,
public class SomeClass { // Example of data: int i; // Example of a constructor public SomeClass(int i) { this.i = i; // this.i refers to the instance variable i as opposed to the argument i } // Example of a function: public void printStuff () { System.out.println (i); } // Main function. Not all classes have a main public static void main (String[] argv) { SomeClass sc = new SomeClass(42) sc.printStuff (); } } // End of class SomeClass
Note three conventions that java programmers tend to follow:
You can have multiple classes in a single file, but only one may be public. The public class name must match the file name. For example the above class SomeClass should live in a file called SomeClass.java. If you have a main method, it should be in the public class if it is to run.
Here are some charming facts about methods:
Modifiers like public are used to indicate the visibility of class members. We use the dot-operator to access methods (or data) from another class, e.g,
public class SomeClass { // Example of data: int i; // Examples of constructors public SomeClass() { i = 0; // provide a default value if called with no args } public SomeClass(int i) { this.i = i; // this.i refers to the instance variable i as opposed to the argument i } // Example of a function: public void printStuff () { System.out.println (i); } // Main function. Not all classes have a main public static void main (String[] argv) { AnotherClass sc = new AnotherClass(42) sc.printStuff (); } } // End of class SomeClass
Even though there is a printStuff method in SomeClass, the programmer has decided to call a printStuff method belonging to another class (presumably because it is better for current purposes.
class AnotherClass { public void printStuff (int i) { } }so that when you java SomeClass the output is:
The integer value is: 42 and thank you for using AnotherClass