In this chapter you will learn:
- What are classes in java and how to create it?
- What is objects and how to initialize it?
- What is methods and how to create it?
- Programming Example
What are classes?
Classes are the blueprint of your program. It is the place where you define variables, methods, constructors, blocks, interfaces and program logic. Once classes are completed you can use it many times by creating its alias name or objects.
How to define class?
You can define class with class keyword as follow:
public class MyClass
What is object and how to initialize it?
An object is an alias of the class which represents class behavior. A class may have many objects with different names. You can define objects as follow:
Class_Name object_name=new Class_Name();
What is method or function?
A method of function is a basic building block of program which contains set of code and referred to by a name. A method is created inside class and can be accessed anywhere in program directly by name or followed by its class name.
How to define method?
It is very easy to define method in java. You can write method as follow:
public void myname()
public String myname()
OK. It’s enough for theory. Let’s understand all these concepts using programming example. In the following program we will create classes, methods and objects.
public static void main(String args)
//Creating Calculator Object
Calculator calc=new Calculator();
//Calling Add() method
//Creating PrintData Class Object
PrintData pdata=new PrintData();
//Calling print() method
//Defining Class Calculator
public int Add(int num1, int num2)
System.out.println("Calculator Class Started...");
return num1 + num2;
//Defining Class PrintData
public void print(int value)
System.out.println("PrintData Class Started.. ");
Calculator Class Started…
PrintData Class Started..
In the above programming example we have done the following job.
- Created 2 separate class
Calculatorclass have a method
Add(int num1, int num2)which requires 2 integer number to process and it returns addition of both number.
PrintDataclass have a method
print(int value)which requires an integer value and print it on screen.
- In the main method I have created object of
CalculatorClass and send 2 integer value for processing.12Calculator calc=new Calculator();result=calc.Add(12,18);
- Next create object of PrintData and used it’s print method for printing output.12PrintData pdata=new PrintData();pdata.print(result);
So, we have explained how to create classes objects and methods in Java. However there are lots of thing in classes but we can’t explain all those things here. It will make this article heavy for understanding. You will learn all those things part by part in the next few chapters. The next chapters explain Constructors in Java.