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

Remove Duplicates from List Using Set.addAll

The Set interface has a method called addAll. This accepts a 'Collection' as the parameter. So if you invoke this method by passing the...

Remove Duplicates from List Using HashSet

The Set is also an interface in the 'Java Collection' framework. Unlike a List, a Set does not allow duplicates. Hence you can...

Java DecimalFormat Class

When you need to format decimal numbers, such as taking three or two decimal places for a number, showing only the integer part of...

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

Â

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

How To Create Maven Project in Eclipse Without Archetype

Maven is a very popular build and dependency management tool. Eclipse is an IDE that helps developers write and run Java code easily. In...

How To Create Singleton Class in Java

Design patterns Overview Design patterns are basically solutions to programming problems that developers normally encounter during software development. Design patterns were first documented by four...

Convert String to Date Using SimpleDateFormat Class

Sometimes, you may need to convert a String to a java.util.Date object. For this, you need to use the SimpleDateFormat class. You need 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...

OTHER TUTORIALS

Getting Started with Apache JMeter

1. Introduction As a developer, you may have tested the functionality of your code hundreds of times during development. This...
- Advertisement -spot_img