Java Classes and Objects

JK 2010 
Created at
Updated at  
7,060 0 0

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 real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.

A Class is like an object constructor, or a "blueprint" for creating objects.


Create a Class

To create a class, use the keyword class:

public class Main {
  int x = 5;
}

Create an Object

In Java, an object is created from a class. We have already created the class named Main, so now we can use this to create objects.

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);
  }
}

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
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);
  }
}

When both files have been compiled:

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

Run the Second.java file:

C:\Users\Your Name>java Second

And the output will be:

5

Java Class Attributes

In the previous chapter, 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:

public class Main {
  int x = 5;
  int y = 3;
}

Accessing Attributes

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

The following example will create an object of the Main class, with the name myObj. We use the x attribute on the object to print its value:

public class Main {
  int x = 5;

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

Modify Attributes

You can also modify attribute values:

public class Main {
  int x;

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

Or override existing values:

public class Main {
  int x = 10;

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

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);
  }
}

Multiple Objects

If you create multiple objects of one class, you can change the attribute values in one object, without affecting the attribute values in the other:

public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main myObj1 = new Main();  // Object 1
    Main myObj2 = new Main();  // Object 2
    myObj2.x = 25;
    System.out.println(myObj1.x);  // Outputs 5
    System.out.println(myObj2.x);  // Outputs 25
  }
}

Multiple Attributes

You can specify as many attributes as you want:

public class Main {
  String fname = "John";
  String lname = "Doe";
  int age = 24;

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println("Name: " + myObj.fname + " " + myObj.lname);
    System.out.println("Age: " + myObj.age);
  }
}

Java Class Methods

You learned from the Java Methods chapter that methods are declared within a class, and that they are used to perform certain actions:

public class Main {
  static void myMethod() {
    System.out.println("Hello World!");
  }
}

myMethod() prints a text (the action), when it is called. To call a method, write the method's name followed by two parentheses () and a semicolon;

public class Main {
  static void myMethod() {
    System.out.println("Hello World!");
  }

  public static void main(String[] args) {
    myMethod();
  }
}

// Outputs "Hello World!"

Static vs. Public

You will often see Java programs that have either static or public attributes and methods.

In the example above, we created a static method, which means that it can be accessed without creating an object of the class, unlike public, which can only be accessed by objects:

public class Main {
  // Static method
  static void myStaticMethod() {
    System.out.println("Static methods can be called without creating objects");
  }

  // Public method
  public void myPublicMethod() {
    System.out.println("Public methods must be called by creating objects");
  }

  // Main method
  public static void main(String[] args) {
    myStaticMethod(); // Call the static method
    // myPublicMethod(); This would compile an error

    Main myObj = new Main(); // Create an object of Main
    myObj.myPublicMethod(); // Call the public method on the object
  }

Access Methods With an Object

// Create a Main class
public class Main {
 
  // Create a fullThrottle() method
  public void fullThrottle() {
    System.out.println("The car is going as fast as it can!");
  }

  // Create a speed() method and add a parameter
  public void speed(int maxSpeed) {
    System.out.println("Max speed is: " + maxSpeed);
  }

  // Inside main, call the methods on the myCar object
  public static void main(String[] args) {
    Main myCar = new Main();   // Create a myCar object
    myCar.fullThrottle();      // Call the fullThrottle() method
    myCar.speed(200);          // Call the speed() method
  }
}

// The car is going as fast as it can!
// Max speed is: 200

Example explained

1) We created a custom Main class with the class keyword.

2) We created the fullThrottle() and speed() methods in the Main class.

3) The fullThrottle() method and the speed() method will print out some text, when they are called.

4) The speed() method accepts an int parameter called maxSpeed - we will use this in 8).

5) In order to use the Main class and its methods, we need to create an object of the Main Class.

6) Then, go to the main() method, which you know by now is a built-in Java method that runs your program (any code inside main is executed).

7) By using the new keyword we created an object with the name myCar.

8) Then, we call the fullThrottle() and speed() methods on the myCar object, and run the program using the name of the object (myCar), followed by a dot (.), followed by the name of the method (fullThrottle(); and speed(200);). Notice that we add an int parameter of 200 inside the speed() method.


Using Multiple Classes

Like we specified in the Classes chapter, it is a good practice to create an object of a class and access it in another class.

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:

  • Main.java
public class Main {
  public void fullThrottle() {
    System.out.println("The car is going as fast as it can!");
  }

  public void speed(int maxSpeed) {
    System.out.println("Max speed is: " + maxSpeed);
  }
}
  • Second.java
class Second {
  public static void main(String[] args) {
    Main myCar = new Main();     // Create a myCar object
    myCar.fullThrottle();      // Call the fullThrottle() method
    myCar.speed(200);          // Call the speed() method
  }
}

When both files have been compiled:

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

Run the Second.java file:

C:\Users\Your Name>java Second

And the output will be:

The car is going as fast as it can!
Max speed is: 200

Java Constructors

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:

// Create a Main class
public class Main {
  int x;  // Create a class attribute

  // Create a class constructor for the Main class
  public Main() {
    x = 5;  // Set the initial value for the class attribute x
  }

  public static void main(String[] args) {
    Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
    System.out.println(myObj.x); // Print the value of x
  }
}

// Outputs 5

Constructor Parameters

Constructors can also take parameters, which is used to initialize attributes.

The following example adds an int y parameter to the constructor. Inside the constructor we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:

public class Main {
  int x;

  public Main(int y) {
    x = y;
  }

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

// Outputs 5

You can have as many parameters as you want:

public class Main {
  int modelYear;
  String modelName;

  public Main(int year, String name) {
    modelYear = year;
    modelName = name;
  }

  public static void main(String[] args) {
    Main myCar = new Main(1969, "Mustang");
    System.out.println(myCar.modelYear + " " + myCar.modelName);
  }
}

// Outputs 1969 Mustang

Static

A static method means that it can be accessed without creating an object of the class, unlike public:

public class Main {
  // Static method
  static void myStaticMethod() {
    System.out.println("Static methods can be called without creating objects");
  }

  // Public method
  public void myPublicMethod() {
    System.out.println("Public methods must be called by creating objects");
  }

  // Main method
  public static void main(String[ ] args) {
    myStaticMethod(); // Call the static method
    // myPublicMethod(); This would output an error

    Main myObj = new Main(); // Create an object of Main
    myObj.myPublicMethod(); // Call the public method
  }
}

Abstract

An abstract method belongs to an abstract class, and it does not have a body. The body is provided by the subclass:

// Code from filename: Main.java
// abstract class
abstract class Main {
  public String fname = "John";
  public int age = 24;
  public abstract void study(); // abstract method
}

// Subclass (inherit from Main)
class Student extends Main {
  public int graduationYear = 2018;
  public void study() { // the body of the abstract method is provided here
    System.out.println("Studying all day long");
  }
}
// End code from filename: Main.java

// Code from filename: Second.java
class Second {
  public static void main(String[] args) {
    // create an object of the Student class (which inherits attributes and methods from Main)
    Student myObj = new Student();

    System.out.println("Name: " + myObj.fname);
    System.out.println("Age: " + myObj.age);
    System.out.println("Graduation Year: " + myObj.graduationYear);
    myObj.study(); // call abstract method
  }
}

Encapsulation

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must:

  • declare class variables/attributes as private
  • provide public get and set methods to access and update the value of a private variable

 

Get and Set

You learned from the previous chapter that private variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public get and set methods.

The get method returns the variable value, and the set method sets the value.

Syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter in upper case:

public class Person {
  private String name; // private = restricted access

  // Getter
  public String getName() {
    return name;
  }

  // Setter
  public void setName(String newName) {
    this.name = newName;
  }
}

Example explained

The get method returns the value of the variable name.

The set method takes a parameter (newName) and assigns it to the name variable. The this keyword is used to refer to the current object.

However, as the name variable is declared as private, we cannot access it from outside this class:

If the variable was declared as public, we would expect the following output:

John

However, as we try to access a private variable, we get an error:

MyClass.java:4: error: name has private access in Person
    myObj.name = "John";
         ^
MyClass.java:5: error: name has private access in Person
    System.out.println(myObj.name);
                  ^
2 errors

Instead, we use the getName() and setName() methods to access and update the variable:

public class Main {
  public static void main(String[] args) {
    Person myObj = new Person();
    myObj.setName("John"); // Set the value of the name variable to "John"
    System.out.println(myObj.getName());
  }
}

// Outputs "John"

Why Encapsulation?

  • Better control of class attributes and methods
  • Class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method)
  • Flexible: the programmer can change one part of the code without affecting other parts
  • Increased security of data

 

Below YouTube content might be helpful for better understanding:

Tags Java Java Classes Java Constructors Java Objects Java Public Functions Java Static Functions Java Static Objects Public Functions Static Functions Static Object Facebook X
Comments 0
Similar posts
  1. Java Packages
    7,154
  2. Java Inheritance (Subclass and Superclass)
    7,159
  3. Java Recursion
    7,181
  4. Java Scope
    7,071
  5. Java Methods
    7,062
  6. Java Polymorphism
    7,036
  7. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    7,804
  8. Java Switch Statements
    7,374
  9. Java Short Hand If...Else (Ternary Operator)
    7,540
  10. Java If ... Else
    7,360
  11. Java Inner Classes
    7,026
  12. Java Math
    7,405
  13. Java Variables
    7,421
  14. Java Comments
    7,957
  15. The Print() Method
    7,133
  16. Java Syntax
    7,405
  17. Java Getting Started
    7,376
  18. What is Java?
    7,072
  19. Machine Learning Types and Programming Languages
    7,209
  20. Java Tutorials associated with AP Computer Science A
    7,557
  21. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,146
  22. Java Servlet Example
    7,101
  23. Difference between Java and Javascript
    7,567
  24. Challenge: One Code Problem Per Day
    1,041
  1. Java Servlet Example
    7,101
  2. How do I replace content that based on the HTML UI Template
    7,136
  3. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,146
  4. Dataset of California Foodbanks
    7,146
  5. Java Tutorials associated with AP Computer Science A
    7,557
  6. Java Inner Classes
    7,026
  7. Java Polymorphism
    7,036
  8. Java Inheritance (Subclass and Superclass)
    7,159
  9. Java Packages
    7,154
  10. Java Abstract Classes and Methods
    7,672
  11. Java Recursion
    7,181
  12. Java Scope
    7,071
  13. Java Methods
    7,062
  14. Java Arrays
    8,611
  15. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    7,804
  16. Java Switch Statements
    7,374
  17. Java Short Hand If...Else (Ternary Operator)
    7,540
  18. Java If ... Else
    7,360
  19. Java Math
    7,405
  20. Java Variables
    7,421
  21. Java Comments
    7,957
  22. The Print() Method
    7,133
  23. Java Syntax
    7,405
  24. Java Getting Started
    7,376
  25. What is Java?
    7,072
Recently updated
  1. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    61
  2. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    140
  3. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    172
  4. The Evolution and Production Reality of Agentic AI
    166
  5. How to Activate or Waive Your UIUC Student Health Insurance
    240
  6. Complete Guide to Building a Machine Learning Model
    290
  7. My life cuts at Las Vegas during Thanksgiving day holiday
    7,369
  8. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    313
  9. Harness vs. OpenClaw: Two Very Different "Agents"
    903
  10. Clean Python Environments: The Power of venv vs. Docker
    771
  11. What is Docker? Why is Docker also useful in a development environment?
    584
  12. UIUC 2026-2027 Academic Calendar
    1,466
  13. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    762
  14. Open-Source LLMs: The AI Revolution
    709
  15. Resume 2.0: Leveling Up for My First Software Gig
    2,084
  16. Not everyone will understand what this man just did
    1,729
  17. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,545
  18. Unpacking IU's Shopper
    709
  19. Jackie Chan's Police Story: The Action Masterpiece
    608
  20. The IVE Story: Identity, 'I AM' Charts, and Influence
    910
  21. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,147
  22. Open Databases for Sex Crime Occurrences in the U.S.
    675
  23. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    2,521
  24. My First Day at University of Illinois-Urvana Champaign
    1,155
  25. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,084
  26. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,156
  27. Sipping the Stars: My Starbucks Adventure
    9,576
  28. Exciting explore at Sequoia National Park
    7,616
  29. My Life Shot at Death Valley
    1,629
  30. Ip Man fights with Muay Thai Master
    900
  31. Mad Clown - Don't Die
    974
  32. How to get Student Enrollment and Degree Verification at UIUC
    4,656
  33. LAX Thanksgiving Rush: A Joyful Reunion
    896
  34. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,079
  35. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    943
  36. 10CM - To Reach You (너에게 닿기를)
    1,127
  37. Feeling weak? Transform yourself at the UIUC ARC!
    1,547
  38. BOYNEXTDOOR - If I Say I Love You
    1,154
  39. The Future of Software Engineer - AI Engineering
    913
  40. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    881
  41. Lie - Legend song by BIGBANG
    7,788
  42. Why ROLLBACK is useful when you work with Google Gemini CLI?
    806
  43. Reimbursement after Vaccination at McKinley Health Center
    974
  44. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    936
  45. Common Questions from UIUC school life in terms of CS Program
    1,074
  46. UIUC Immunization Compliance
    1,165
  47. LEE CHANHYUK's songs really resonate with my soul - Time Stop! Vivid LaLa Love, Eve, Endangered Love ...
    1,064
  48. LEE CHANHYUK - Endangered Love (멸종위기사랑)
    1,068
  49. Cupid (OT4/Twin Ver.) - LIVE IN STUDIO | FIFTY FIFTY (피프티피프티)
    844
  50. Common methods to improve coding skills
    958