Java Classes and Objects


Java Classes/Objects

Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, as well as its attributes and methods. For example: in real life, a car is a thing. The car has attributes, such as weight and color, and methods, such as driving and braking.

A class is like an architect, or a "plan" for creating things.


Create a Class

To create a class, use the keywords class:


Example

Create a class named "Main" with a variable x:

public class Main {
            int x = 5;
          }
          


Create an Object

In Java, an object is created from a class. We've already created a class called Main, so now we can use this to build things.

To create a Main object, specify a class name, followed by an item name, and use a new keyword:


Example

Create an object called "myObj" and print the value of x:

public class Main {
            int x = 5;
          
            public static void main(String[] args) {
              Main myObj = new Main();
              System.out.println(myObj.x);
            }
          }
          


Multiple Objects

You can create multiple objects in one category:


Example

Create two objects of Main:

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 a class item and access it in another class. This is often used for better class planning (one class has all the features and methods, while the other class has the main() method (code to use)).

Remember that the java file name must match the class name. In this example, we created two files in the same directory / folder:

  • Main.java
  • Second.java

Main.java
public class Main {
            int x = 5;
          }
          


Second.java
class Second {
            public static void main(String[] args) {
              Main myObj = new Main();
              System.out.println(myObj.x);
            }
          }
          

Once both files have been merged:


C:\Users\Your Name>javac Main.java
C:\Users\Your Name>javac Second.java

Launch the Second.java file:


C:\Users\Your Name>java Second

And the output will be:


5