Java Classes and Objects
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its attributes and methods.
For Example, in a real life, a car is an object. The car has attributes, such as color and model, and methods, such as braking system and drive.
A class is like an object constructor, or a “blueprint” for creating objects.
Create a class
To create a class, we use the keyword class:
Example
public class ClassExample { String text = "Hello World"; }
Note: The class name should always start with the upper case as per the Java Syntax rules and the name of the file should always match with the class name.
Create an object
In Java, an object is created from a class. To create an object, specify the class name followed by object name, and use the keyword new:
Example
public class ClassExample { String text = "Hello World"; public static void main (String args[]){ ClassExample myObj = new ClassExample(); System.out.println(myObj.text); } }
Output
Hello World
Creating Multiple Objects
Multiple Objects can be created of one class.
Example
Here we create two objects of ClassExample:
public class ClassExample { String text = "Hello World"; public static void main (String args[]){ ClassExample myObj1 = new ClassExample(); ClassExample myObj2 = new ClassExample(); System.out.println(myObj1.text); System.out.println(myObj2.text); } }
Output
Hello World Hello World
Using Multiple Classes
An object for a class is created and can be accessed it in another class. Through this, we can better organize the classes (once class can hold all the attributes and methods, while the other class holds the main() method (from where the code execution starts).
There can be only one public class in the Java file but there can be as many class files in the Java file.
In this example, we create two files under the same directory/folder.
· MyClass.java
· MainClass.java
MyClass.java
public class MyClass { String text = "Hello World!"; }
MainClass.java
public class MainClass { public static void main (String args[]){ MyClass myObj = new MyClass(); System.out.println(myObj.text); } }
Output
We compile both the files separately and run the MainClass.java file.
Hello World!