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

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...

Convert List to Array Using ToArray Without Param

Java provides a toArray method on the 'List' interface. This can be used to convert a 'List' to an array. Since there are are...

Convert List to Array Using ToArray With Param

There is an overloaded version of the toArray method. This accepts an array as a parameter and returns a result array that is of the same...

Concatenate Strings Using String.concat()

The String class has a method called concat. It accepts as parameter a String value and concatenates it with the current String. The following...

Â

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

Format Decimal Numbers Using Locale

If you want to create a DecimalFormat instance for a specific Locale, create a NumberFormat and cast it to a DecimalFormat. The java.text.DecimalFormat class is...

Java Tutorial #1 – Variables and Data Types

Table of Contents Introduction 1. Variables 2. Data Types Primitive Data Types Integer Data Types Decimal Data Types Character Data Types Boolean Data Types Reference...

Maven CLI Options and Switches Reference

Maven offers a good set of commands and CLI Options to carry out wide range of Dev tasks. Most of these commands are in...

How To Create Maven Project Using Command Line

Maven project can be easily created using built-in plugins from the popular IDEs such as Eclipse and IntelliJ IDEA. However, in scenarios where you...

OTHER TUTORIALS

Convert List to Array Using ToArray Without Param

Java provides a toArray method on the 'List' interface. This can be used to convert a 'List' to an...
- Advertisement -spot_img