Java Classes and Objects: Foundation of Object-Oriented Programming
Learn about Java's object-oriented programming (OOP) paradigm, where everything is structured around classes and objects. Discover how classes define attributes and methods, and how objects represent real-world entities like a car, with properties like weight and color, and actions like drive and brake.
Java Classes and Objects
Java is an object-oriented programming language where everything is associated with classes and objects, each having attributes and methods. For example, in real life, a car is an object with attributes like weight and color, and methods like drive and brake.
Create a Class
To create a class in Java, use the keyword class
:
Syntax
public class Main {
int x = 5;
}
Create an Object
In Java, an object is created from a class. Once a class like Main is created, objects can be instantiated:
Example
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
Output
5
Multiple Objects
You can create multiple objects of the same class:
Example
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 create objects of a class and access them from another class for better organization:
Example
// File: Main.java
public class Main {
int x = 5;
}
// File: Second.java
class Second {
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
Ensure the Java file names match the class names for proper compilation and execution.