Java Tutorial

What is Java


Control Statements


Java Object Class


Java Inheritance


Java Polymorphism


Java Abstraction


Java Encapsulation


Java Array

Java OOPs Misc


Object and Class in Java

In this page, we will learn about java objects and classes. In object-oriented programming technique, we design a program using objects and classes.

Object is the physical as well as logical entity whereas class is the logical entity only.

Object in Java

An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or logical (tangible and intangible). The example of intangible object is banking system.

An object has three characteristics:

  1. State:represents data (value) of an object.
  2. behavior:represents the behavior (functionality) of an object such as deposit, withdraw etc.
  3. identity:Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But, it is used internally by the JVM to identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to write, so writing is its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the instance(result) of a class.

Object Definitions:

  1. Object is a real world entity.
  2. Object is a run time entity.
  3. Object is an entity which has state and behavior.
  4. Object is an instance of a class.

Class in Java

A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

  1. fields
  2. methods
  3. constructors
  4. blocks
  5. nested class and interface

Syntax to declare a class:

class {
method;
field;
}
// example
public class JavaClassName {
String str;
int age;
String blueprint;
void M1() {
}
void m2() {
}
void m3() {
}
}


Instance variable in Java

A variable which is created inside the class but outside the method, is known as instance variable. Instance variable doesn't get memory at compile time. It gets memory at run time when object(instance) is created. That is why, it is known as instance variable.

Method in Java

In java, a method is like function i.e. used to expose behavior of an object.

Advantage of Method

  1. Code Reusability
  2. Code Optimization

new keyword in Java

The new keyword is used to allocate memory at run time. All objects get memory in Heap memory area.

Object and Class Example: main within class

In this example, we have created a Student class that have two data members id and name. We are creating the object of the Student class by new keyword and printing the objects value.
Here, we are creating main() method inside the class.

package com.ashu;
public class Java64bitDemo {
public Java64bitDemo(String name) {    // Constructor has one parameter, like name.
System.out.println("Its Name is :" + name );
}
public static void main(String []args) {
// Following statement would create an object myObject
Java64bitDemo myObject = new Java64bitDemo( "Java64bit" );
}
}


output: Its Name is :Java64bit

Object and Class Example: main outside class

In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's see a simple example, where we are having main() method in another class.

We can have multiple classes in different java files or single java file. If you define multiple classes in a single java source file, it is a good idea to save the file name with the class name which has main() method.

package com.ashu;
class Student{
int id;
String name;
}
//Creating another class Java64bitDemo
class Java64bitDemo{
public static void main(String args[]){
Student st=new Student();
System.out.println(st.id);
System.out.println(st.name);
}
}


output: 0 null

There Are three Ways to initialize object

  1. By reference variable
  2. By method
  3. By constructor

1) Object and Class Example: Initialization through reference

Initializing object simply means storing data into object. Let's see a simple example where we are going to initialize object through reference variable.

package com.ashu;
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}


output: 101 Sonoo


We can also create multiple objects and store information in it through reference variable.

package com.ashu;
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}


output : 101 Sonoo 102 Amit


2) Object and Class Example: Initialization through method

In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method.

class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){
System.out.println(rollno+" "+name);
}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}


output: 111 Karan 222 Aryan


As you can see in the above figure, object gets the memory in heap memory area. The reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.

3) Object and Class Example: Initialization through constructor

We will learn about constructors in java later.

Object and Class Example:

package com.ashu;
class Employer{
int id;
String name;
String department;
void insert(int i, String n, String d) {
id=i;
name=n;
department=d;
}
void display(){System.out.println(id+" "+name+" "+department);}
}
public class Java64bitDemo {
public static void main(String[] args) {
Employer e1=new Employer();
Employer e2=new Employer();
e1.insert(3860,"Prateek","HR");
e2.insert(3861,"Santosh","IT");
e1.display();
e2.display();
}
}


output:3860 Prateek HR 3861 Santosh IT


Object and Class Example: Rectangle

package com.ashu;
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){
System.out.println(length*width);
}
}
class Java64bitDemo{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(23,10);
r2.insert(3,9);
r1.calculateArea();
r2.calculateArea();
}
}


output:230 27


What are the different ways to create an object in Java?

There are many ways to create an object in java. They are:

  1. By new keyword
  2. By newInstance() method
  3. By clone() method
  4. By deserialization
  5. By factory method etc.

Anonymous object

Anonymous simply means nameless. An object which has no reference is known as anonymous object. It can be used at the time of object creation only.

new Java64bitDemo();//anonymous object

If you have to use an object only once, anonymous object is a good approach. For example:

package com.ashu;
public class Java64bitDemo {
public String message(){
return "Print anonymous object";
}
public static void main(String[] args) {
System.out.println(new Java64bitDemo().message()); //We have used message() method on new Java64bitDemo() which is an anonymous object.
}
}


output: Print anonymous object


Calling method through reference:

Java64bitDemo c=new Java64bitDemo();
c.display();


Calling method through anonymous object

new Java64bitDemo().message();


Let's see the full example of anonymous object in java.

package com.ashu;
class Java64bitDemo{
void fact(int n)
{
int fact =1;
for (int i =1; i <= n; i++)
{ fact =fact*i;
}
System.out.println("Factorial is :" +fact);
}
public static void main(String[] args) {
new Java64bitDemo().fact(5);
}
}


output:Factorial is:120


Creating multiple objects by one type only

We can create multiple objects by one type only as we do in case of primitives.

int x = 2 , y = 3;


Initialization of refernce variables:

java64bit b1=new java64bit()
b2=new java64bit();//creating two objects

Consider the following example, where we will create an array of Employee objects and print their details in a for loop.

package com.ashu;
import java.util.ArrayList;
import java.util.List;
public class Java64bitDemo implements Cloneable {
private int data;
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Java64bitDemo(int data){
this.data = data;
}
public static void main(String[] args) {
List testerList = new ArrayList();
testerList.add(new Java64bitDemo(5));
testerList.add(new Java64bitDemo(6));
testerList.add(new Java64bitDemo(7));
testerList.add(new Java64bitDemo(8));
for(Java64bitDemo tester : testerList){
System.out.println(tester.getData());
}
}
}


output:5 6 7 8


Initialization of reference variables in java

package com.ashu;
public class Java64bitDemo {
public static void main(String[] args) {
// Declaration of Reference variable
Reference ref1, ref2;
// ref3 is declared final, ref3 can't be reassigned
// or refer to different object
final Reference ref3;
// assign ref1 with object Reference
ref1 = new Reference("This is the first reference variable", 1);
// access method getNumber() of object Reference through
// variable ref1
int number = ref1.getNumber();
System.out.println("number= " + number);
// assign ref2 with object Reference
ref2 = new Reference("This is the second reference variable", 2);
// passing ref2 as method parameter of printText() method
Java64bitDemo.printText(ref2);
// assign ref3 with object Reference
ref3 = new Reference("This is the third reference variable", 3);
// try to reassign ref3 will cause a compile-time error
// ref3 = new Reference("Try to reassign", 3);
}
public static void printText(Reference reference) {
String text = reference.getText();
System.out.println(text);
}
}
class Reference {
private int number;
private String text;
Reference(String text, int number) {
this.text = text;
this.number = number;
}

public String getText() {
return text;
}
public int getNumber() {
return number;
}
}


output: number= 1 This is the second reference variable


Let's see the example

package com.ashutosh;
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){
System.out.println(length*width);
}
}
class Java64bitDemo{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(8,3);
r2.insert(2,14);
r1.calculateArea();
r2.calculateArea();
}
}


output:24 28


Real World Example: Account

package com.ashu;
class BankAccount{
long account_no;
String account_name;
float amount;
//Method to initialize object
void insert(long i,String n,float ashu){
account_no=i;
account_name=n;
amount=ashu;
} //deposit method
void deposit(float ashu){
amount=amount+ashu;
System.out.println("Rs."+ashu+" deposited");
}
//withdraw method
void withdraw(float ashu){
if(amount System.out.println("Insufficient Balance");
}else{
amount=amount-ashu;
System.out.println("Rs."+ashu+" withdrawn");
}
}
//method to check the balance of the account
void checkBalance(){
System.out.println("Balance is: "+amount);
}
void mentainBalances()
{
if(amount<10000){
System.out.println("Balance is low mentain Ten thousand:"+amount);
}
}
//method to display the values of an object
void display(){
System.out.println("Bank Account no is:"+account_no+" "+"Account Holder:"+account_name+" "+"Total Balance:"+amount);
}
}
//Creating a test class to deposit and withdraw amount
class Java64bitDemo{
public static void main(String[] args){
BankAccount ba=new BankAccount();
ba.insert(159555523688L,"ashutosh Kumar",20000);
ba.display();
ba.checkBalance();
ba.deposit(64356);
ba.checkBalance();
ba.withdraw(74356);
ba.checkBalance();
ba.mentainBalances();
}
}


output: Bank Account no is:159555523688 Account Holder:ashutosh Kumar Total Balance:20000.0
Balance is: 20000.0
Rs.64356.0 deposited
Balance is: 84356.0
Rs.74356.0 withdrawn
Balance is: 10000.0


Copyright 2017 Design& Development