Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: Core Java Basics. No Comments on Java class and object

In this article, we will learn what is a Java class and object and also how to create Java classes and objects.

 

Introduction

 

According to object orientation, a class is a template or blueprint for creating objects. An object is an instance of a class. To understand a Java class and object easily let’s consider a real world example of boys and girls as shown below:

 

Java class and object

 

In the above example, the classes are boy and girl. Objects are Faiza, Rita, Shelly, Mary, Rose, George, Ken, Prasad, Kishore and Jeevan.

 

If we declare the boy as a class in Java, it will be something as shown below:

class Boy
{
	String name;
	String address;
	int age;
	void tellName(){ };
	void tellAddress(){ };
	void tellAge(){ };
}

 

Declaring a class for girl is left to you as an exercise 😉

 

Now, let’s create an object, say, George. In Java, we create objects as shown below:

Boy george = new Boy();

 

Again creating other objects is left as an exercise for you.

 

Java Class

 

To declare a class in Java, we use the Java keyword class. Remember that all the keywords in Java are lowercase letters. The class keyword is followed by class name which is Boy in my example.

 

According to Java’s convention, every first letter in a word must be a uppercase letter. All the predefined Java classes follow this convention. Some of the predefined Java classes are:

 

Object
Exception
Throwable
System
PrintStream
Scanner
StringTokenizer

 

Class name is followed by the body of the class delimited by braces { and }, which contains the class members. For a complete list of class members look at this: structure of a Java class.

 

In the above example of class Boy, we have three variables: name, address and age. We also have three methods (functions in C and C++) namely, tellName(), tellAddress() and tellAge().

 

If you are creating a class, it means that you are creating a new user-defined type. That class (type) will be used to create objects later.

 

General syntax for declaring a class in Java is as shown below:

class ClassName
{
	//Class Members
}

 

In the above example, the class members are the three variables and the three methods. So, there are a total of 6 class members in our example of Boy class.

 

Rules for writing class names or any other identifiers (variable names, method names etc…)

  • A name must start with a letter or an underscore ( _ ) or a dollar sign ($). Beginning the name with a letter is recommended. From second character on wards a name can contain digits or numbers also.
  • White spaces and special symbols like %, @, * are not allowed in the name.
  • Uppercase characters are distinct from lowercase characters. Names are case-sensitive i.e var is different from VAR.
  • Keywords or reserved words can’t be used for names. For example, goto cannot be used for a name as it is a reserved word in Java.

 

Some valid class names will be:

 

Student
Contact
UserDetails
Registration
Marks
Sem2Marks
_Names
$Product

 

Some invalid examples for class names are:

 

2Inventory (Name cannot start with a number)
User Details (Name cannot contain white spaces)
Cart@Shop (Name cannot contain special symbols)
switch (Keywords cannot be used in names)

 

Java Object:

 

Syntax for creating an object in Java is as shown below:

ClassName   object-reference = new   ClassName();

 

An example for creating an object for the Boy class declared above is as shown below:

Java Object

 

As already denoted in the figure, Boy is the name of the class for which we are creating the object. Remember that objects doesn’t exist without a class. obj is the reference to the object. The actual object is created by the new operator which is one of the Java’s keywords.

 

The new keyword creates the object dynamically (at runtime) in the RAM (Random Access Memory) and returns the reference (address) of the object created. That reference is stored in obj which will be used to access the object in future.

 

The last part of the line is Boy() which is a constructor. For now remember that a constructor is a method which will have the same name as class name. Constructors will be explained in detail in a future article.

 

Above object creation can be separated into two lines as shown below:

Boy obj;
obj = new Boy();

 

In the first line, by default, obj refers to null. The memory representation of the above two lines is as shown below:

Object memory representation Java

 

After creating an object using the above syntax, we can access the class members like variables and methods using the dot (.) operator or also known as dot separator. So, we can access the three variables (fields) name, address and age as shown below:

obj.name = “George”;
obj.address = “Los Angels, USA”;
obj.age = 23;

 

The general syntax for accessing a class member is as shown below:

object_reference.member_name;

 

By joining all the pieces together, the complete program will be as shown below:

class Boy
{
	String name;
	String address;
	int age;
	void tellName(){ };
	void tellAddress(){ };
	void tellAge(){ };
	public static void main(String[] args)
	{
		Boy obj = new Boy();
		obj.name = "George";
		obj.address = "Los Angels, USA";
		obj.age = 23;
		System.out.println("Name of the boy is: "+obj.name);
		System.out.println("Address of the boy is: "+obj.address);
		System.out.println("Age of the boy is: "+obj.age);
	}
}

 

In lines 15,16 and 17 you can see that there is a + operator in the println statement. Here, + is not a addition operator. If one operand of the + operator is a string, then + behaves as a concatenation operator. So, the right side value will be converted into a string and is joined with the left side string.

 

Output of the above program will be:

Name of the boy is: George
Address of the boy is: Los Angels, USA
Age of the boy is: 23

 

Differences between a class and an object

 

Class Vs Object

 

Some of the questions related to Java classes and objects:

 

1) Are object references same as pointers in C and C++?

A: Although references are very similar to pointers (both store address of the memory location), references cannot be manipulated as we can with pointers. In C and C++, one can increment a pointer value or do other operations on it. Such operations are not allowed on references in Java.

 

2) Where are objects created?

A: Objects are created dynamically in the heap area inside RAM (Random Access Memory).

 

3) Can classes exist without objects?

A: Yes. But vice-verse is not true.

 

4) What does an instance actually mean?

A: As already mentioned above, the fields of a class does not contain any values. An object contains its own value for every field. For example, if we consider the object of Boy class (see above), the values for the fields name, address and age are: “George”, “Los Angels, USA” and 23 respectively. These values are collectively known as the state of the object. This is why an object is known as an instance of the class as it has its own values for all the fields.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

Your email address will not be published. Required fields are marked *