Classes and Objects
Multiple Objects
You can create multiple objects of one class:
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
Using Multiple Classes
You can also create an object of a class and access it in another
class. This is often used for better organization of classes (one
class has all the attributes and methods, while the other class
holds the main() method (code to be executed)).
Remember that the name of the java file should match the
class name. In this example, we have created two files in the
same directory/folder:
•Main.java
•Second.java
Main.java
Second.java
Java Class Attributes
In the previous lesson, we used the term "variable"
for x in the example (as shown below). It is actually
an attribute of the class. Or you could say that class
attributes are variables within a class.
Modifying Attributes
Example #1:
Example #2: