Class and Package in Java with Example

In this chapter, we will learn Class and Package in Java.

1. What is Class in Java?

As we discussed in our previous post, Java is an Object-Oriented programming language.

Also, everything is considered as an object in Java. For Example, a car is an object.

Therefore, it has attributes like colour and weight, behaviour like it moves and methods like the brake, accelerate, etc.

Therefore, Class is just a template or blueprint to create such objects and we can add certain attributes using variables and methods.

To define a class in Java, we use “class” keyword and a class can contain fields, methods, block, constructor, etc.

1.1 Syntax to declare class:

class className{
	//variables;
	//methods;
}

Example: “HelloWorld” class with a variable “number”

class HelloWorld{
	 int number = 5;
}

Always Remember:

  • A class can contain variables, methods, constructors, subclasses, fields, interfaces, etc.
  • To write any particular functionality in Java we have to define a class ( interfaces in other cases).
  • For writing any sort of Java code we need to declare a class.

2. What is Package in Java?

Packages are similar to folders in Java, Inside the package, you can define your classes and interfaces.

However, it helps you to organize your files in a manner and to avoid conflicts in the names of classes and interface.

  • You can’t declare two files with the same name within the same package.
  • You can declare two files with the same name in the different package.
  • Each package should have a unique name.
  • Packages make easy to locate any class or interface.
  • Packages play a major role in encapsulation.

2.1 Naming Convention:

  • Packages should be named in reverse order like – com.masterincoding.practise

2.2 Creating Packages:

  • Without IDE: Simply create folders and subfolder and put your java file inside that.
  • With IDE (Eclipse): Right Click on project and select create package then enter package name.

2.3 Using Packages:

Syntax: package packageName;

Example:

package com.mic.practise;

class DemoClass {
	
}

Syntax: import packageName.className; ( importing class from a different package)

Example:

package com.mic.practise;

import com.mic.demo.AdditionClass; //importing class from another package

public class DemoClass {
	
}

Always Remember:

// import the LinkedHashMap class from util package.
import java.util.LinkedHashMap; 

// import all the classes from util package
import java.util.*;

In conclusion, class and package in Java are very important and you should remember all naming conventions and rule to declare class or package.