Java Tutorial #7 Part 1 – Classes & Objects

Introduction to Java Classes, Objects and Methods

Table of Contents

Classes are a very important concept in Java. Java code always needs to be written in a class. In this article, we will be taking a very close look at classes and understanding their syntax and semantics.

Classes and objects

A class defines a new data type. Once defined, this new type can be used to create objects of that type. So, a class acts like a template and provides the structure for an object.

Class Syntax

A class generally contains data and the code that operates on the data. The following is the general syntax of a class:

class classname{

	type var1;
	type var2;
	type varn;

type method1(parameters){
}

type method2(parameters){
}

type methodn(parameters){
}

}

The class keyword is followed by the name to be given to the class. The data in the class is present in the form of variables. These are known as instance fields. The code in the class is present in the form of methods. A class can contain any number of instance fields and methods. Also, both instance fields and methods are optional, a class can contain either instance fields or methods or both. Instance fields and methods are collectively referred to as members of a class.

Defining a class

A class can be defined by using the ‘class’ keyword followed by the name to be given to the class. Let us first create a very basic class that does not have instance fields and methods:

class StudentDemo {

}

This code defines a class called StudentDemo and this StudentDemo acts as a template using which Student objects can be created.

Creating an object

A class can be used to create objects of that type. Multiple objects can be created from the same class. All objects of a class conform to the structure provided by the class. The new keyword can be used to create ab object of a class.

The following code demonstrates creating an object of type Student:

public class StudentDemo {

	public static void main(String[] args) {
		
		Student student1 = new Student();
	}

}

This code defines a class called StudentDemo. The main method creates a Student object called student1. The new keyword is followed by the class name and parentheses. This is known as a constructor of the class. Constructors will be covered in the next part of this article.

Instance Fields

A class can also contain data in the form of instance fields. Instance fields add state to a class. Each object of a class has its own copy of the instance fields.

Defining instance Fields

Instance fields can be defined by specifying their data type followed by a variable name. Let us add some instance fields to the Student class:

public class Student {
	
	String name;
	double marks;
	
}

This code specifies two instance fields in the Student class. name is of type String and marks is of type double. When a Student object is created, Java allocates memory to the name and marks field.

Accessing instance Fields

Java provides the dot operator (.) to access instance fields. The object name should be followed by the dot operator and followed by the field name. The following code demonstrates assigning some values to the name and marks fields in the Student class:

Student student1 = new Student();
		
student1.name = "John Doe";
student1.marks = 93;

This code creates a Student object called student1. It assigns the value John Doe to the name field of student1 and the value 93 to the marks field of student1.

You can create another Student object as follows:

Student student2 = new Student();
		
student2.name = "Lucia Kane";
student2.marks = 78.5;

This code creates another Student object called student2 with different values for name and marks.

Methods

As mentioned earlier, a class can contain code in the form of methods. Methods generally operate on the data in the class.

Defining a method

A method can be defined by specifying the name of the method followed by the code to be placed in the body of the method. Let us add a method to the Student class:

public class Student {
	
	String name;
	double marks;
	
	void printDetails() {
		System.out.println("Student "+name+" has "+marks+" marks");
	}
	
}

This code specifies a method called printDetails on the Student class. It simply prints the values for the name and marks field.

Invoking a method

Just like instance fields, a method can also be accessed via the dot operator. The following code demonstrates invoking the printDetails method:

Student student1 = new Student();
		
student1.name = "John Doe";
student1.marks = 93;
		
student1.printDetails();

This code creates a Student object called student1 and assigns some values to the name and marks field. It then invokes the printDetails method. So, this causes the code in the printDetails method to be executed. So, when you run the code snippet above, it will print the following to the console:

Student John Doe has 93.0 marks

Conclusion

So, just to summarise, a class acts like a template that can be used to create objects of the class. A class can contain instance fields and methods. In the next part of this article, we will be taking a closer look at methods and also exploring constructors.

Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

JAVA TUTORIALS

Recent Posts

RELATED POSTS

Format Decimal Numbers using Strings Within Pattern

As mentioned in earlier posts, the java.text.DecimalFormat class is used to format decimal numbers via predefined patterns specified as String. Apart from the decimal separator,...

Concatenate Strings Using StringBuffer.append()

In addition to String, Java has the java.lang.StringBuffer and java.lang.StringBuilder classes. These can also be used to concatenate Strings. The advantage of these...

Remove Duplicates from List Using For-Loop

The simplest way to remove duplicates from a 'List' is to use a for-loop. The following code snippet demonstrates this method. First, the code creates...

Convert String to java.time.LocalDate with Formatter

The LocalDate class has an overloaded parse() method. In addition to the String Date, it accepts a DateTimeFormatter instance that specifies the format of...

Â

CHECKOUT 'HOW-TOs'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string...

MORE ON CODEX

MORE IN THIS CATEGORY

COM Components and Scripting Process

Although this article should not concern you at all as a 'script developer' as long as you are aware of creating a reference to...

Java Tutorial #6 – Jump Statements

Introduction The break statement is used to stop further execution. It can be used either in a loop or within a switch statement. Break Statement The break...

Convert List to Array Using For-Loop

The simplest way to convert a List to an array is to use a for-loop. The following code snippet demonstrates this method. First, the code...

Concatenate Strings Using StringBuffer.append()

In addition to String, Java has the java.lang.StringBuffer and java.lang.StringBuilder classes. These can also be used to concatenate Strings. The advantage of these...

OTHER TUTORIALS

How To Install Pacman For Git on Windows

The 'Git for Windows' by default does not come with MSYS2 package manager called 'Pacman' and hence it is...
- Advertisement -spot_img