0% found this document useful (0 votes)
3 views8 pages

Classes and Objects

The document explains the concept of creating multiple objects from a single class in Java, illustrated with a code example. It also discusses the organization of classes, where one class contains attributes and methods while another contains the main execution code. Additionally, it clarifies that class attributes are essentially variables defined within a class.

Uploaded by

tongquin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

Classes and Objects

The document explains the concept of creating multiple objects from a single class in Java, illustrated with a code example. It also discusses the organization of classes, where one class contains attributes and methods while another contains the main execution code. Additionally, it clarifies that class attributes are essentially variables defined within a class.

Uploaded by

tongquin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

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:

You might also like