Introduction
Java class is the basic building block of Java programming language. Java class is a template used to create objects and to define data types and methods.Java class objects should have the basic class properties. This article will explain how Java classes work with code examples.
What are Java Classes?
Java class is the basic concept of object-oriented programming language. Java class is a user-defined template or blueprint where objects, data members, and methods are defined and a set of instructions to build a specific object type. The variables and methods of the same Java class are common for all the class objects.
In Java, the class keyword is used to define a Java class.
How is a Java Class defined?
Syntax
class <class-name>
{
[data members]
[method];
}
Code Example
class MyClass
{
int x = 5; //data member;
void fun() //
{
System.out.println("This is method");
}
}
What are the three major components of the Java class?
1) What are the class variables in Java?
A variable is a reserved memory location to hold a value. In other words, when we want to store any value and give it a name, that value takes a reserved space in memory, and it’s called a variable.
A variable has any value which is located in the memory.
Syntax
<access specifier > < data type > < variable name > = < value > ;
How can we declare the Variable?
Code Example
int x ; (int is a data type and x is a variable name).
int y;
int x , y;
int x = 4 , y = 5;
byte p = 65;
double pi = 3.1415;
char q = ‘s’ ;
What are the different types of Variables in Java?
1. Local Variable in Java
A variable declared inside any methods, constructors, and blocks is known as a local variable. It is created after the creation of the method, constructor, block, and a local variable is not visible to the class and not accessed by the class. Its scope is limited because it is used locally in the method.
For example, first, we create a class and a method. Afterward, declare two local variables inside the method.
Code Example
public class LocalVariableExm {
void message() { //it is a method.
int p; // declaration of Local Variable.
int x = 10; // declaration and initialization of Local Variable.
}
}
Static Variable in Java
A static variable is a very important type of Variable. We use static keywords with the Variable. Hence, it’s called a static variable. Static Variable is declared inside the class and outside the method, constructor, and block. The static variable belongs to the class, not an Object, and is stored in static memory. Its default value is 0, which we can call the static Variable with its class name. Hence, creating an object in a static variable is unnecessary.
For example, first, we create a class and three variables outside the method, where two variables are static variables.
Code Example
public class StaticVariableExm {
int p;
static int q = 10; // Static Variable with initialization
static int r; // Static Variable declaration
void message() {
}
}
Instance Variable in Java
An instance variable is declared inside the class but outside the method, constructor, or block. It has the most comprehensive scope because it is globally visible to the class. It is created at the time of object creation. When the instance variable is created at that time, it takes space in the heap memory, and is called through the object, and the default value is 0.
For example, first, we create a class and two instance variables outside the method.
Code Example
public class InstanceVariableExm {
int a; // Declaration of instance variable.
int b = 10; // Declaration and initialization of instance variable.
void message() {
}
}
2) What is Constructor in Java?
A constructor is like a special method in Java, which is used to initialize an object of a Java class Constructor is very important for every Java class. If we don't declare the constructor, the compiler creates a default constructor of a Java class.
A constructor must be the same name as a Java class. It does not have a return type.
What are the different types of constructors in Java?
In Java, Constructors can be divided into three types.
Default constructor in Java
The default constructor has no parameter, and if we do not declare a constructor, the compiler automatically creates a default constructor of that Java class.
Syntax
<class-name>() { }
In the following program, we create a default constructor and print a message as an output. The complete program is listed below.
public class DefaultConstructor{
DefaultConstructor() {
System.out.println("This is default constructor example");
}
public static void main(String args[]) {
DefaultConstructor d = new DefaultConstructor();
}
}
The output of the above code generates the following output.
The default constructor provides the default value to the object, like 0 or null. The value depends on their type.
In the following program, we are not creating a constructor compiler to provide it by default and provide default values. The complete program is listed below.
public class DefaultConstructor2 {
String name;
String number;
void display() {
System.out.println(name + "," + number);
}
public static void main(String args[]) {
DefaultConstructor2 t = new DefaultConstructor2();
t.display();
}
}
The output of the following code generates the following output.
Parameterized constructor in Java
A constructor that has parameters is called a parameterized constructor in Java. We use the parameterized constructor to provide different values to distinct objects.
In the following program, we create a parameterized constructor with two parameters. The complete program is listed below.
public class ParameterizedConstructor {
String name;
int salary;
ParameterizedConstructor(String n, int s) {
name = n;
salary = s;
}
void display() {
System.out.println("Employee name is: " + name + "," + "and salary is : " + salary);
}
public static void main(String args[]) {
ParameterizedConstructor e = new ParameterizedConstructor("Rohan", 25000);
e.display();
}
}
The output of the following code generates the following output.
Copy constructor in Java.
Copy constructor in Java class is a special constructor that takes the same class as an argument. A copy constructor is used to provide a copy of the specified object.
A copy constructor is used when we want to copy an object that is heavy to initiate. The complete program is listed below.
public class CopyConstructor {
int empid;
public CopyConstructor(int b) {
empid = b;
}
public void disp() {
System.out.println("Employee id is :" + empid);
}
public static void main(String[] args) {
CopyConstructor e = new CopyConstructor(1002);
e.disp();
}
}
The output of the following code generates the following output.
3) What are the methods in the Java class?
Methods are used to perform certain actions, also known as functions. A method is a block of code that only runs when called. You can pass data, known as parameters, into a method.
Why do we use Methods in Java Classes?
To reuse code: define it once and use it many times.
How to create a method in the Java class?
A method must be declared within a class. It is defined with the method's name, followed by parentheses ().
Syntax
class <class-name> {
modifier dataType methodName () {
//block of code to be executed } }
//calling the method from anywhere
className.methodName();
The complete program is listed below.
public class MethodExample {
static void myMethod() {
System.out.println("Hello World!");
}
public static void main(String[] args) {
myMethod();
}
}
The output of the following code generates the following output.
Methods with parameters in Java
A parameter is a value you can pass to a method in Java. Then the method can use the parameter as though it were a local variable initialized with the Variable's value passed to it by the calling method.
Types of Parameters in Java
Formal Parameter: A variable and its type as they appear in the prototype of the function or method.
Syntax
function_name(datatype variable_name)
Actual Parameter: The Variable or expression corresponding to a formal parameter that appears in the function or method call in the calling environment.
Syntax
func_nme(variable name(s));
The complete program is listed below.
public class ParameterizedMethodExample {
static void myMethod(String name) {
System.out.println(name);
}
public static void main(String[] args) {
myMethod("CsharpCorner");
}
}
The output of the following code generates the following output.
Note. Java class declaration can contain objects, class members, access modifiers, and constructors.
What are Objects in Java class?
An object is a fundamental concept of oops like java classes .objects are like an entity with a state and behavior. Like cars, mobiles, pencils, cats, etc. A car has states(its color, name, and brand) and behavior(running). Objects are instances of a java class, and objects can be tangible and intangible. Objects represent identity, which uniquely identifies it. One car number plate is a different number of other cars. So, it is the car's identity that is unique.
Objects represent the value of an object, like car name, color, and brand. Objects represent the functionality of an object, like a car's functionality running.
How to create an object in Java class?
In Java new keyword is used to create an object.
Syntax
<class-name> [object-name] = new <class-default-conetructor>
Example Code
class ObjectCreationExample
{
public static void main(String args[]) {
ObjectCreationExample s = new ObjectCreationExample(); // create an object.
}
}
What are Data Members in Java class?
Data members are those whose memory space is created every time whenever an object is created. Data members are always meant to store a specific value.
Syntax
Data type v1,v2,v3,........vn;
class DataMember
{
int v1,v2,v3;
float f1,f2;
}
What are Access Modifiers in Java class?
The access Modifiers give the accessibility (scope) of a java class, data member, method, or constructor. Access Modifiers help us set the access level for our java class, variables, and methods.
What are the different types of access modifiers?
There are four types of Java access modifiers.
- public
- private
- protected
- default
The following table lists access modifiers.
Access Modifiers |
Keywords |
Public access modifier |
public |
Private |
private |
Protected |
protected |
Default |
no keyword used |
1) Public Access Modifier.
The public access modifier is accessible in all places. It has the most comprehensive scope among all other modifiers. Variables, methods, and constructors are declared public within a public class visible to any class in the java program. Hence, it doesn't matter whether these classes are in the same package or another package.
The complete program is listed below.
Step 1. First, we create a Java class PublicExample in which we declare the method show():
public class PublicExample {
public void show() {
System.out.println("Public access modifier example");
}
}
Step 2. Second, we create a class called PublicAccess which we call the method of PublicExample class.
public class PublicAccess {
public static void main(String args[])
{
PublicExample obj = new PublicExample();
obj.show();
}
}
The output of the following code generates the following output.
2) Private Access Modifier
The private access modifier is accessible only within and not outside the class. Data members, methods, or constructors declared are strictly controlled. The private access modifier can not be accessed anywhere outside the class.
A Java class can not be private except for the nested class.
The complete program is listed below.
Step 1. First, we create a Java class PrivateExample in which we declare a private method run():
public class PrivateExample{
private void run() {
System.out.println("Scooter is running");
}
}
Step 2. Second, we create a class PrivateAccess in which we call the method of PrivateExample class:
public class PrivateAccess{
public static void main(String args[]) {
PrivateExample s = new PrivateExample();
s.run(); //compile time error
}
}
The output of the following code generates the following output.
Note
In this example, we create two Java classes PrivateExample and PrivateAccess. PrivateExample contains private method run(). If we want to access the private method outside the class, it gives the compile-time error.
3) Protected access modifier.
The protected access modifier is accessible within and outside the package but through inheritance only.
The protected access modifiers can be applied to the variables, methods, and constructors but they can't apply to Java classes. Variables, methods, and constructors are protected in a parent class and can be accessed by the child class in other packages.
The complete program is listed below.
Step 1. First, we create a public Java class ProtectedExample in package pack1 in which we declare a protected method display().
package pack1;
public class ProtectedExample{
protected void display() {
System.out.println("Protected access modifier example");
}
}
Step 2. Second, we create a public Java class ProtectedAccess in package pack2, which we call the method of ProtectedClass class.
package pack2;
import pack1.*;
public class ProtectedAcces extends ProtectedClass{
public static void main(String args[]) {
ProtectedAccess p = new ProtectedAccess();
p.display();
}
}
The output of the above code generates the following output.
4) Default access modifier
When we don't use any modifier, it is treated as a default access modifier in Java. The default access modifier is only accessible only within the package.
Any Java class, Variable, method, and constructor, the default access modifier, is accessible only by the classes in the same package. The default access modifier is not used for variables and methods within an interface.
The complete program is listed below.
Step 1. First, we create a default Java class named DefaultExample in package pack1 which we declare a method msg():
package pack1;
class DefaultExample {
void msg() {
System.out.println("Default access modifier example");
}
}
Step 2. Second, we create a default Java class DefaultAccess package named pack2 in which we call the method of DefaultClass class:
package pack2;
import pack1.*;
class DefaultAccess{
public static void main(String args[]) {
DefaultClass d = new DefaultClass();// compile time error
r.msg(); // compile time error
}
}
The output of the above code generates the following output.
Note
In this example, we create two Java classes DefaultClass and DefaultAccess. DefaultClass is a default Java class that can't be accessed outside the package. So, it gives the compile-time error.
How many types of classes are in Java?
There are three major types of Java classes.
- Abstract Java Classes
- Nested Java Classes
- Final Java Classes
- Singleton Java class
1) What is an Abstract class in Java?
Before Abstract Java classes, we should know about Abstraction in Java.
Abstraction
In Java, Abstraction is a procedure to hide the implementation details from the user and provides only functionality to the user. For example, when we want to calculate some data in a calculator, we use its keys but don't know how it works internally.
So, when we use an abstract keyword with any class, this class is called an abstract Java class. It provides only essential things to the user and hides the internal process from the user.
- Abstract Java class can have abstract methods and non-abstract methods.
- If a class has an abstract method, this class must be an abstract Java class.
- If we want to use an abstract class, it must be extended and its methods implemented.
- If we extend an abstract Java class, we have to provide the implementation for all abstract methods in it.
The complete program is listed below.
Step 1. First, we create an abstract Java class named Employee in which we declare an abstract method called work().
abstract class AbstractClass {
abstract void work();
}
Step 2. Second, we create a public Java class named WomanEmployee in which we access the method work(), and its implementation is given by WomanEmployee class.
public class AbstractClass2 extends AbstractClass{
void work() {
System.out.println("Abstract class Example");
}
public static void main(String args[]) {
AbstractClass p = new AbstractClass2();
p.work();
}
}
The output of the following code generates the following output.
2) What are the Nested Java classes?
The Java programming language allows you to define a class within another class. We use the nested class to logically group the class and interface in one place. It can be more readable and maintainable and can access all the members of the outer class(public, private, protected).
Syntex
class OuterClass{
......
class InnerClass{
//Nested Java class
}
}
Advantages of nested class in Java
1. Nested Java classes show a special type of relationship; it can access all the members of the outer class, including private.
2. Nested Java classes are mainly used to make our program more readable and maintainable because it logically groups the classes and interfaces in one place.
3. Nested classes require less code to write.
Types of nested classes.
1. Non-static Nested Classes
2. Static-Nested Classes
Non-static nested classes are also known as inner classes in Java.
Member inner class in Java
Member inner class is created inside the class but outside the method. It is a non-static inner class. Creating an inner member class in Java is simple. We need to write a class inside the class. The inner class can be private, and once we declare an inner class as confidential, it can not be accessed from an object outside the outer class.
Syntax
class Outer{
class Inner
{
// Member inner class
}
}
The complete program is listed below.
public class MemberClassExample {
private int data = 30;
class MemberClassInner {
void msg() {
System.out.println("data is " + data);
}
}
public static void main(String args[]) {
MemberClassExample obj = new MemberClassExample();
MemberClassExample.MemberClassInner in = obj.new MemberClassInner();
in.msg();
}
}
The output of the following code generates the following output.
Note
In the example, we create a display() method in the inner member class, which access the private data member of the outer class.
Anonymous inner class in Java
The classes which have no name are called anonymous inner classes in Java. It must be used when we have to override the method of the class and interface.
We can declare and initiate them at the same time. The complete program is listed below.
public class AnonoymousClassExample {
public static void main(String[] args) {
AnonoymousDemo a = new AnonoymousDemo() {
public void message() {
System.out.println("Anonymous Inner Class Example");
}
}; // anonymous class body closes here
//a contains an object of anonymous subclass of AnonoymousClassExample.
a.message();
}
}
class AnonoymousDemo {
public void message() {
System.out.println("Message");
}
}
The output of the following code generates the following output.
Local inner class in Java
A Java class created inside the method is called a local inner class Java; if we want to call the methods of the local inner class, then we must initiate this class inside the method.
The complete program is listed below.
public class LocalInnerClassExample {
private int data = 30;
void display() {
class Local {
void msg() {
System.out.println(data);
}
}
Local l = new Local();
l.msg();
}
public static void main(String args[]) {
LocalInnerClassExample obj = new LocalInnerClassExample();
obj.display();
}
}
The output of the following code generates the following code.
Static nested class in Java
A static class can not access non-static data members and methods. It can access static members of the outer class, whether private, public, or protected, and can only be accessed through the outer class name. When a static class is created inside another Java class, it is called a static nested class.
Syntax
class Outer{
static NestedClass {
// Static Nested class
}
}
The complete program is listed below.
public class StaticNestedClassExample {
static int age = 30;
static class StaticClassAccess {
void display() {
System.out.println("Employee age is " + age);
}
}
public static void main(String args[]) {
StaticNestedClassExample.StaticClassAccess a = new StaticNestedClassExample.StaticClassAccess();
a.display();
}
}
The output of the following code generates the following output.
3) Final Java class
When we use the final with any class, it is called a final Java class. A final class can't be inherited. If any class is declared final, all its methods are implicitly declared as final.
Syntax
final class <class-name>{
// code
}
The complete program is listed below.
final class FinalClassExample {
}
class Manager extends FinalClassExample { // Compile time error
void work() {
System.out.println("working hard");
}
public static void main(String args[]) {
Manager m1 = new Manager();
m1.work();
}
}
The output of the following code generates the following output.
Note
In this example, we create a final Java class named FinalClassExample and another Java class named Manager. We try to inherit the final class, but the program makes a compile-time error.
4) Singleton Java Class
In object-oriented programming, a singleton class is a class that can have only one object at a time. Singletons often control access to resources, such as database connections or sockets. The intention is to create a single instance of an object of classes that are expensive to create during runtime and try to reuse the same object. Such objects are mainly immutable.
Some basic rules are required to implement a singleton class.
1. A constructor should be private.
2. Declare a static variable object of the class.
3. Declare a static method to return the instance.
The complete program is listed below.
Step 1. First, we create a singleton class named SingletonClassExample.
public class SingletonClassExample {
private static SingletonClassExample singleton = new SingletonClassExample();
public static SingletonClassExample getInstance() {
return singleton;
}
protected static void demoMethod() {
System.out.println("demoMethod for singleton");
}
}
Step 2. Second, we create a public class named SingleTonDemo for accessing the singleton class.
public class SingletonDemo {
public static void main(String[] args) {
SingletonClassExample tmp = SingletonClassExample.getInstance();
tmp.demoMethod();
}
}
The output of the following code generates the following output.
Summary
In this tutorial, we learned about various Java classes and how to use them in our java program.