Sitemap
Bora Fazli

Bora Fazli

Java Classes (Part 1)

2 min readApr 21, 2023

--

What is OOP?

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods.

Get Bora Fazli’s stories in your inbox

Join Medium for free to get updates from this writer.

Object-oriented programming has several advantages over procedural programming:

  • OOP is faster and easier to execute
  • OOP provides a clear structure for the programs
  • OOP helps to keep the Java code DRY “Don’t Repeat Yourself”, and makes the code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time
Press enter or click to view image in full size

Create a Class:

To create a class, use the keyword class.

public class Main {
int x = 5;
}

Remember from the Java Syntax chapter that a class should always start with an uppercase first letter, and that the name of the java file should match the class name.

Create an Object:

To create an object of Main, specify the class name, followed by the object name, and use the keyword new.

public class Main {
int x = 5;

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

You can access attributes by creating an object of the class, and by using the dot syntax (.):

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); // Output 5
System.out.println(myObj2.x); // Output 5
}
}

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.

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

Modify Attributes:

You can also modify attribute values.

public class Main {
int x = 5;

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

If you don’t want the ability to override existing values, declare the attribute as final.

public class Main {
final int x = 10;

public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}

--

--