Java Classes and Objects

JK1536 
Created at Jul 16, 2023 07:06:36
Updated at May 10, 2024 14:05:52 
  1,142   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 Share on Facebook Share on X

◀ PREVIOUS
Java Recursion

▶ NEXT
Java Abstract Classes and Methods

  Comments 0
OTHER POSTS IN THE SAME CATEGORY

Java Servlet Example

(created at Feb 19, 2024)

How do I replace content that based on the HTML UI Template

(created at Feb 12, 2024)

Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows

(created at Jan 28, 2024)

Dataset of California Foodbanks

(updated at Feb 12, 2024)

Java Tutorials associated with AP Computer Science A

(updated at Jun 15, 2024)

Java Inner Classes

(updated at May 10, 2024)

Java Polymorphism

(created at Jul 18, 2023)

Java Inheritance (Subclass and Superclass)

(updated at May 10, 2024)

Java Packages

(updated at May 10, 2024)

Java Abstract Classes and Methods

(updated at Jan 02, 2024)

Java Recursion

(updated at May 10, 2024)

Java Scope

(updated at May 10, 2024)

Java Methods

(updated at May 10, 2024)

Java Arrays

(updated at May 13, 2024)

Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue

(updated at May 13, 2024)

Java Switch Statements

(updated at May 15, 2024)

Java Short Hand If...Else (Ternary Operator)

(updated at May 15, 2024)

Java If ... Else

(updated at May 15, 2024)

Java Math

(updated at May 15, 2024)

Java Variables

(updated at May 15, 2024)

Java Comments

(updated at May 15, 2024)

The Print() Method

(updated at May 10, 2024)

Java Syntax

(updated at May 15, 2024)

Java Getting Started

(updated at May 15, 2024)

What is Java?

(created at Jul 07, 2023)

UPDATES

LoL Worldcup - Worlds 2024 Finals Opening Ceremony Presented by Mastercard ft. Linkin Park, Ashnikko and More!

(created at Nov 18, 2024)

The hippie perm of NewJeans' Danielle 

(updated at Nov 15, 2024)

Danielle was featured on the UK Fashion Pop Magazine cover

(updated at Nov 15, 2024)

IU Photos from her family trip

(updated at Nov 09, 2024)

Men vs. Women Taekwondo Sparring - Beautiful Taekwondo Star Tammy's Dazzling Roundhouse Kicks

(updated at Nov 09, 2024)

Legendary Taekwondo Match of the Korean National Sports Festival in High School Division

(updated at Nov 09, 2024)

Legendary Taekwondo 540 degree Kick - Champion Hyun-goo Noh

(created at Nov 09, 2024)

The difference between Equation and Formula

(created at Nov 08, 2024)

Lengendary Turkish Taekwondo player Tazegul at 2015 WTF World Taekwondo Championships

(updated at Nov 08, 2024)

World Rank #2 - Turkey TKD Legend Servet Tazegül

(created at Nov 07, 2024)

Irvine Restaurant American-Style Vietnamese Food Brodard (ft. Ultimate Spring Roll)

(updated at Nov 03, 2024)

Block unwanted URLs for comfortable web browsing with Chrome Addon - URL Blocker

(updated at Nov 01, 2024)

The Gigant Cowboys of Virginia City, Nevada 1889 - AI Generated Photos

(updated at Oct 28, 2024)

Sushi Koto: The "Ohtani" Sushi Spot in Irvine

(created at Oct 26, 2024)

Modern Web Indexing Technology - IndexNow

(updated at Oct 24, 2024)

Key Differences in Gen Z/Alpha/Zalpha based on Upbringing and Life Experiences

(updated at Oct 22, 2024)

Zalpha Generation: A New Term for the Children of Gen Z and Millennials

(updated at Oct 22, 2024)

Zalpha: A Global Trend, Not Just a Distant Concept

(updated at Oct 22, 2024)

The Generation Corona (+ Gen Z) is grappling with how to communicate and live alongside Gen Alpha

(updated at Oct 21, 2024)

Porto's Bakery in Buena Park: A Review from Irvine

(created at Oct 20, 2024)

Starship, Super Heavy, Successful Ground Landing

(updated at Oct 19, 2024)

Understanding Texas A&M - a leading research university, receiving significant funding from both the government and private sector

(updated at Oct 18, 2024)

Exploring UC Davis (aka UCD) - Schools and Majors

(updated at Oct 16, 2024)

AI Generated One-Punch Man with old school style TV shows

(updated at Oct 15, 2024)

One-Punch Man Analysis: The Bald Cape Hero

(updated at Oct 15, 2024)

Why One-Punch Man is a Great Action Anime?

(updated at Oct 15, 2024)

The War of Dogs and Cats - AI-Generated Video by AlgoContent

(updated at Oct 15, 2024)

Dreamy indie band Room402's song "Like the Moon in the Daytime" with AI-generated video

(updated at Oct 15, 2024)

One-Punch Man's Saitama: Motivational Quotes and the Hero's Story

(updated at Oct 13, 2024)

Cream Pan: A Must-Visit Japanese Bakery in Fountain Valley

(created at Oct 13, 2024)

NewJeans - Chicago Live at Lollapalooza 2023

(updated at Oct 12, 2024)

One-Punch Man: Saitama's Promotion Journey and the Final Goal as a Hero

(updated at Oct 12, 2024)

One-Punch Man Combat Power Rankings

(created at Oct 12, 2024)

Difference in HEAD and GET for HTTP Request - why HEAD Request could be used for DDoS Attack?

(updated at Oct 11, 2024)

AI Generated Sailor Moon Video - In the name of justice, I will not forgive you!

(updated at Oct 11, 2024)

Snack that makes my mouth happy when winter comes from the U.S - Hot Pockets

(updated at Oct 11, 2024)

One-Punch Man Crafted by AI - Witness the Limitless Power of Sora AI

(updated at Oct 11, 2024)

My chrome browser is annoying me by Language - How do I change the default language?

(updated at Oct 11, 2024)

AI-Generated Berserk: A Majestic Sight

(updated at Oct 11, 2024)

Global Electronic Medicine Trends and Market Outlook 

(updated at Oct 09, 2024)

What is Google Analytics?

(updated at Oct 09, 2024)

Understanding the Key Differences Between GIS and LBS: Purpose, Technology, and Applications

(updated at Oct 09, 2024)

The Evolution and Applications of Geographic Information Systems: From Thematic Mapping to Efficient Data Analysis and Management

(created at Oct 09, 2024)

Quantum computer and qubit generation method

(updated at Oct 08, 2024)

Green Premium, Eco-Certified Building

(updated at Oct 08, 2024)

Why Two Path Authentication is Essential - My Microsoft Account is Gone!

(updated at Oct 08, 2024)

Amazon's Return-to-Office Mandate: A Bold Move or a Step Backwards?

(updated at Oct 08, 2024)

Exploring UC Merced (aka UCM) - Schools and Majors

(updated at Oct 08, 2024)

Understanding Rose-Hulman Institute of Technology

(updated at Oct 08, 2024)

Understanding Rensselaer Polytechnic Institute based in New York

(updated at Oct 08, 2024)