Java Programming
1 Class Terminology
In Java, classes can contain not just functions (a.k.a. methods), but also data.
To run a class, we must define a main method (but not all classes have a main method). Unlike python, there's no need to import if the two files are in the same project.
Classes can be instantiated as objects. The class provides a blueprint that all instances (objects) will follow.
A variable or method defined in a class is also called a member of that class.
Example with Terminology
/* penguin.java */
public class penguin {
public int age; // Instance variables, can have as many of these as you want
public static String binomen = "Spheniscidae"; // Static variable, shared by all instances of the class
/* Constructor (similar to a method, but not a method), determines how to instantiate the class */
public penguin(int age) {
this.age = age;
}
/* Static Method, can be called without creating an instance of the class */
public static void makeNoise() {
System.out.println("Aw!");
}
/* Non-static method, a.k.a. Instance Method, can only be called by creating an instance of the class */
public void addage(int years) {
age += years;
}
public static penguin compareAge(penguin p1, penguin p2) {
if (p1.age > p2.age) {
System.out.println("p1 is older");
return p1;
} else {
System.out.println("p2 is older");
return p2;
}
}
}
/* Main.java */
public class Main {
public static void main(String[] args) {
penguin p1 = new penguin(5); // Instantiation and Assignment, ok to separate them
p1.makeNoise(); // Aw! (Not Recommended, but works)
p1.addage(2); // Calling non-static method
System.out.println(p1.age); // 7
penguin p2 = new penguin(3);
penguin older = penguin.compareAge(p1, p2); // p1 is older, return p1
// Static methods must access instance variables via a specific instance!
penguin.makeNoise(); // Aw! (Calling static method)
penguin.addage(2); // Error, cannot call non-static method without an instance
penguin.name("Penguin"); // Syntax Error!
}
}
Initialing an array
int[] arr1 = new int[5]; // Array of 5 elements, all initialized to 0
int[] arr2 = {1, 2, 3, 4, 5};
arr1 = [0] * 5
arr2 = [1, 2, 3, 4, 5]
Last modified: 25 November 2024