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

Concatenate Strings Using String.join()

Java 8 has added a static join method to the String class. This concatenates Strings using a delimiter. Performance wise, it is similar to...

Convert List to Array Using Stream with Param

There is an overloaded version of the Stream.toArray method which can be used to return a result array that is of the same data...

Introduction to Apache Maven

1. What is Maven When you write a software application, there are many steps in it like adding the necessary JAR files, compiling the source...

Create Basic Hibernate Program

Hibernate is an ORM framework that helps in accessing database tables from Java code. It is an object-oriented way of accessing database tables and...

Â

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

Concatenate Strings Using String.join() for Collections

There is an overloaded version of the String.join method that accepts as parameter an Iterable implementation. Since all Collection classes implement the Iterable interface,...

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

Remove Duplicates from List Using LinkedHashSet

Another implementation of the Set interface is LinkedHashSet. LinkedHashSet maintains the order of elements and helps to overcome the HashSet limitation. The following code...

Convert List to Array Using Stream without Param

Java 8 has added the Stream API that helps to easily perform bulk operations on Collections. A new method called stream() has been added...

OTHER TUTORIALS

How To Customize GitBash For Windows

By default the GitBash prompt settings / configuration come from shell script called 'git-prompt.sh'. This is usually hosted inside...

JMeter Framework Project

- Advertisement -spot_img