Java Objects and Classes – Learn how to Create & Implement

Last updated on Nov 26,2019 12.4K Views
Sr Research Analyst at Edureka. A techno freak who likes to explore... Sr Research Analyst at Edureka. A techno freak who likes to explore different technologies. Likes to follow the technology trends in market and write...

Java Objects and Classes – Learn how to Create & Implement

edureka.co

Objects and classes are considered to be the meat and potatoes of any OOPs based language. Since Java is one of the most prominently used Object-oriented programming languages it becomes very necessary to know these concepts by heart. Thus, I bring you this article, where I will be giving you a complete overview of Java objects and classes.

Below are the topics covered in this article:

Classes and Objects in Java are two such concepts which go hand in hand. You can’t learn one without having the knowledge of the other. Together they form the building blocks of Java. So, let’s quickly jump into the basics and see what actually are Java objects and classes.

What is a Java Class?

A class in Java is a blueprint from which an object is created. It is a logical entity that helps in defining the behavior and properties of an object. A class can only be accessed from outside via its instance. Every class in Java must belong to some package. Packages in Java are nothing but a group of similar types of classes, interfaces, and subpackages.

The classes in Java are generally classified under two categories:

1. Built-in Classes

Built-in classes in Java are the classes which come bundled within predefined packages in Java. Predefined packages are the packages which are developed by Sun MicroSystems and are provided as a part of JDK (Java Development Kit) to help out a java programmer. A few of the majorly used built-in classes are:

  1. java.lang.String
  2. java.lang.System
  3. java.lang.Exception
  4. java.lang.Object
  5. java.lang.Class
  6. java.util.Date
  7. java.util.HashMap
  8. java.util.ArrayList
  9. java.util.Iterator
  10. java.lang.Thread

2. User-Defined/ Custom Classes

As the name suggests, a custom or user-defined class is a class that is created by a user. It will contain the class members as defined by the user.

You will see how to create a class in the next section of this Java objects and classes article.

How to Create a Class in Java?

Creating a class is really simple in Java. Below is a basic skeleton of a Java class:

<access specifier> class  <classname>{
//classbody
}

In order to create a full-fledged custom class, you need to know what are the various elements a class is made up of. A Java class generally consists of the following:

1. Fields

Fields of a class are used to define the properties or state attributes of the class objects. Thus they are declared within the body of the class. The general syntax to declare a class field is given below:

public class EduDemo{
	// A field declaration
    //<<modifiers>> <<data type>> <<field name>> = <<initial value>>;
	public int var = 1101;

}

2. Methods

A method in Java is a collection of a statement which determines the behavior of a class object. They are generally used to modify the state of a class field. By using methods you can also delegate tasks in other objects. Below I have listed down a few properties of a method:

Below is a simple example to define and invoke a method in a Java class:

public class EduDemo{
	//Defining a no argument method
	public void show(){
		System.out.println(“Welcome to Edureka’s Tutorial”);
	}

	//Defining a two argument method
	public void add(int a, int b) {
		int sum = a+b;
		System.out.println(sum);
        }

	public static void main(String[] args) {
		//Initializing variables
		int var1 = 10;
		int var2 = 20;

		System.out.println(“Edureka Objects and Classes in Java”);

		//Invoking methods
		show();

		System.out.println("Sum of given numbers is "+ add(var1,var2));
	}
}

3. Constructors

A constructor in Java is used to initialize an object of a class immediately after the object is created. A constructor must have its name same as its class. In Java, every class has a constructor known as the default constructor but you can add more according to your requirement.

 The general syntax for a constructor declaration is:

<<Modifiers>> <<Constructor Name>>(<<parameters list>>) throws <<Exceptions list>> {..}

Below is an example of the same:

public class EduDemo{
	public EduDemo() {
	//default constructor
	}

	public EduDemo(String name) {
	// This constructor has one parameter
	}

}

You can learn more about the constructors by referring to our article on Java Constructors.

4. Blocks

A Block in Java is a group of one or more statements enclosed within braces. There are two types of blocks in Java:

A static block in Java is the block which is executed only once at the time of class loading. A static block is also known as a static initialization block. A class can have more than one static blocks.  The general syntax for a Static Block declaration is:

public class EduDemo{
	static{
		//block body
	}
}

An instance block in Java is the block which is executed whenever an object is created. A static block is also known as instance initialization block. An instance block is executed in the order they are written after the constructor makes the call to super.  The general syntax for an Instance Block declaration is given below:

public class EduDemo{
	{
		//block body
	}
}

5. Nested Classes

A class defined within another class is called a Nested class.

class EduDemo{
	//EduDemo class body

	class InnerClassDemo{
	//class body
	}

}

I hope by now you know how to create a class. But there are certain rules that you must abide by while creating a class in Java.

Rules to Create a Class

  1. A Java class must have the class keyword followed by the class name, and class must be followed by a legal identifier.
  2. The class name must start with a capital letter and if you are using more than one word to define a class name, every first letter of the latter words should be made capital.
  3. There should not be any spaces or special characters used in a class name except the dollar symbol($) and underscore(_).
  4. A Java class can only have public or default access specifier.
  5. It must have the class keyword, and class must be followed by a legal identifier.
  6. It can extend only one parent class. By default, all the classes extend java.lang.Object directly or indirectly.
  7. A class may optionally implement any number of interfaces separated by commas.
  8. The class’s members must be always declared within a set of curly braces {}.
  9. Each .java source file can contain any number of default classes but can only have one public class.
  10. Class containing the main() method is known as the Main class as it will act as the entry point to your program. 

Now that you know how to create a class, let’s now dive a little deeper and see the types of classes availed by Java.

Types of Classes in Java

There are basically three types of classes that are supported by Java:

1. Concrete Class

A normal class is technically a concrete class containing methods, class variables, constructors, blocks and everything. Below is a basic example of a concrete class in Java:

//concrete class
class eduDemo{
	//class body
}

2. Abstract Class

An abstract class is a class which is defined with the keyword abstract will have at least one abstract method (i.e a method without body) within. Abstract classes without any abstract method in it cannot be instantiated but can only be inherited.

//abstract class
abstract class EduDemo{
	//abstract method
	abstract void show();
}

3. Interfaces

Interfaces are similar to classes except a Java Interface can only contain method signatures and fields. In order to use an interface, it must be implemented by a class.

public interface EduInterface{
	public void show();
	public void run();
}

public class eduDemo implements EduInterface{
	public void show(){
		//implementation
	}
	public void run(){
		//implementation
	}
}

So that was all about Java classes. Let’s now move to the second part of this Java objects and classes article and see what are Java Objects and why do we need them to access a class.

What is an Object in Java?

An object in Java is the real-world entity which has its own property and behavior. These are considered to be the fundamental concepts of Java and uses classes as their blueprints. A Java program can have as many objects as required. An object in Java typically insists of the following:

  1. State: This is represented by the attributes and properties of an object.
  2. Behavior: This is defined by the methods of an object
  3. Identity: This provides a unique name to an object and also enables the communication between two or more objects.

Let’s understand the concept of an object using a real-world example.

Suppose we have an object called Mobile. It will have some identity like its model, attributes such as color, RAM, price, and behavior such as text, on, off, etc. All the instances of the class Mobile share the same set of attributes and the behavior. Here one thing you must remember is that attribute values of each object will be unique. Moreover, a single Java class can have any number of instances.

Now that you know what is an object in Java, let’s now learn how to create an object in the next section of this Java objects and classes article.

How to Create a Java Object?

There are three simple steps to create a Java object which are listed below:

Below is an example of creating an object in Java.

public class EduDemo{
	public EduDemo() {
		// Default Constructor
		System.out.println(“This is a default constructor” );
	}
	public EduDemo(String name) {
		// This constructor has one parameter
		System.out.println(“Hello: ” + name );
		System.out.println(“Welcome to Edureka’s Tutorial”);
   }

   public static void main(String []args) {
   	//Creating an object using default constructor
   	EduDemo myObj = new EduDemo();

   	//Creating an object using parameterized constructor
   	EduDemo myObj = new EduDemo( “Max” );
   }
 }

So, that was all about creating an object in Java. With this, we come to an end of this article on Java Classes and objects. Hope I was able to keep the concepts clear and concise. If you want to know more about Java you can refer to our other Java Blogs.

Now that you have understood what are Java Classes and Objects, check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA Training and Certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Java Classes and Objects” article and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES