0% found this document useful (0 votes)
115 views21 pages

Unit-2: Object

An object in Java is an instance of a class that has both state and behavior. The document defines an object as having two characteristics - state, which represents an object's data or value, and behavior, which represents an object's functionality or methods. A class is a template or blueprint that defines common properties and is used to create objects. The document provides examples of classes like Lamp and objects like specific lamp instances to demonstrate how objects acquire state and behavior from their class. It also describes how to define classes, create objects, and access members of classes through objects in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views21 pages

Unit-2: Object

An object in Java is an instance of a class that has both state and behavior. The document defines an object as having two characteristics - state, which represents an object's data or value, and behavior, which represents an object's functionality or methods. A class is a template or blueprint that defines common properties and is used to create objects. The document provides examples of classes like Lamp and objects like specific lamp instances to demonstrate how objects acquire state and behavior from their class. It also describes how to define classes, create objects, and access members of classes through objects in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Unit-2

Object
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.

Java is an object-oriented programming language. It is based on the concept of objects.


These objects share two characteristics:
 state (fields)
 behavior (methods)

An object has 2 characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object .

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

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

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

For example
Bicycle is an object

State-current gear, two wheels, No. of gears Etc

Behavior- breaking, changing gear Etc

Java Class
Before you create objects in Java, you need to define a class. A class is a blueprint for the object.
We can think of the class as a sketch (prototype) of a house. It contains all the details about the
floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.
Since many houses can be made from the same description, we can create many objects from a
class.

What is a 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:

o Fields
o Methods
o Constructors
o Blocks
o Nested class 

How to define a class in Java?


Here's how we can define a class in Java:

class ClassName {
// variables
// methods
}

For Example

class Lamp {

// instance variable
boolean isOn;

// method
void turnOn() {
isOn = true;
}

// method
void turnOff() {
isOn = false;
}
}
Java Objects
An object is called an instance of a class. For example, suppose
Animal is a class then cat, dog, horse and so on can be considered as object of animal class.

Here is how we can create objects in Java:

className object = new className();

How to access members?


Objects are used to access members of the class. We can access members (call methods and access
instance variables) by using the  .  operator. For example,
class Lamp {
turnOn() {...}
}

// create object
Lamp l1 = new Lamp();

// access method turnOn()


l1.turnOn();

Similarly, the instance variable can be accessed as:

class Lamp {
boolean isOn;
}

// create object
Lamp l1 = new Lamp();

// access method turnOn()


l1.isOn = true

Program:- WAP to access data members and member functions of


class with objects in java
class Lamp {
boolean isOn;

void turnOn() {
// initialize variable with value true
isOn = true;
System.out.println("Light on? " + isOn);

void turnOff() {
// initialize variable with value false
isOn = false;
System.out.println("Light of? " + isOn);
}
}

class Main {
public static void main(String[] args) {

// create objects l1 and l2


Lamp l1 = new Lamp();
Lamp l2 = new Lamp();

// call methods turnOn() and turnOff()


l1.turnOn();
l2.turnOff();
}
}

Output

Light on? True

Light off? False


3 Ways to initialize object
There are 3 ways to initialize object in Java.

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

1) Object and Class Example: Initialization through reference

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

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

Output:

1o1 corona

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

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="prakash";  
  s2.id=102;  
  s2.name="Amit";  
  //Printing data  
  System.out.println(s1.id+" "+s1.name);  
  System.out.println(s2.id+" "+s2.name);  
 }  
}  

O/p
101 prakash
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,"MS Dhoni");  
  s1.displayInformation();  
  s2.displayInformation();  
 }  
}  

O/p
111 Karan
222 MS Dhoni
3) Object and Class Example: Initialization through a constructor

class Employee{  
    int id;  
    String name;  
    float salary;  
    void insert(int i, String n, float s) {  
        id=i;  
        name=n;  
        salary=s;  
    }  
    void display()
{System.out.println(id+" "+name+" "+salary);}  
}  
public class TestEmployee {  
public static void main(String[] args) {  
    Employee e1=new Employee();  
    Employee e2=new Employee();  
    Employee e3=new Employee();  
    e1.insert(101,"ajeet",45000);  
    e2.insert(102,"irfan",25000);  
    e3.insert(103,"nakul",55000);  
    e1.display();  
    e2.display();  
    e3.display();  
}  
}  

O/p

101 ajeet 45000.0


102 irfan 25000.0
103 nakul 55000.0
What is java method?
in computer programming, a function is a block of code that performs a specific task.

In object-oriented programming, the method is a jargon used for function. Methods are bound to a class and they
define the behavior of a class.

Types of Java methods


Depending on whether a method is defined by the user, or available in the standard library, there are two types of
methods in Java:

 Standard Library Methods


 User-defined Methods

Example: Java Method


Let's see how we can use methods in a Java program.

class method {

public static void main(String[] args) {


System.out.println("Method encountered ");

// method call
myMethod();

System.out.println("Method was executed successfully!");


}

// method definition
void myMethod(){
System.out.println("I am inside of method definition so printing from inside myMethod()!");
}
}

Output:
Method encountered.
I am inside of method definition so Printing from inside myMethod().
Method was executed successfully!
Let's see another example,

class method {

public static void main(String[] args) {

// create object of the Output class


Output obj = new Output();
System.out.println("About to encounter a method.");

// calling myMethod() of Output class


obj.myMethod();

System.out.println("Method was executed successfully!");


}
}

class Output {

// public: this method can be called from outside the class


void myMethod() {
System.out.println("Printing from inside myMethod().");
}
}

Output:
About to encounter a method.
Printing from inside myMethod().
Method was executed successfully!

What are the advantages of using methods?


1. The main advantage is code reusability. We can write a method once, and use it multiple times. We do
not have to rewrite the entire code each time. Think of it as, "write once, reuse multiple times". 
2. Methods make code more readable and easier to debug
Access Modifiers in Java

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.
We can change the access level of fields, constructors, methods, and class by applying the access modifier
on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.

In c++, classes belong to name space, just like a library/package and in java, classes belong to
package.

1) Private
The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class, so
there is a compile-time error.

Class A{  
private int data=40;  
private void msg()
{System.out.println("Hello java");}  
}  
  
public class Simple{  
 public static void main(String args[])
{  
   A obj=new A();  
   System.out.println(obj.data);//Compile Time Error  
   obj.msg();//Compile Time Error  
   }  
}  

2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only
within package. It cannot be accessed from outside the package. It provides more accessibility than
private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.

class A{  
  void msg()
{System.out.println("Hello");}  

class B{  
  public static void main(String args[]){  
   A obj = new A();//Compile Time Error  
   obj.msg();//Compile Time Error  
  }  
}  

3) Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.

It provides more accessibility than the default modifier.

Example of protected access modifier


In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.

public class A{  
protected void msg()
{System.out.println("Hello, I am Protected case");}  
}  
class B extends A{  
  public static void main(String args[]){  
   B obj = new B();  
   obj.msg();  
  }  
}  

Output: Hello, I am protected case

4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Example of public access modifier

public class A{  
public void msg()
{System.out.println("Hello, I am public one");}  
}  
class B{  
  public static void main(String args[]){  
   A obj = new A();  
   obj.msg();  
  }  
}

Output: Hello, I am public one


To summary, remember the order of access modifiers from the least restrictive to
the most restrictive:
public > protected > default > private
                

This keyword in java


There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.

Usage of java this keyword

Here is given the 5 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this() can be used to invoke current class constructor.
3. this can be passed as an argument in the method call.
4. this can be passed as argument in the constructor call.
5. this can be used to return the current class instance from the method.

this: to refer current class instance variable


The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves
the problem of ambiguity.

Understanding the problem without this keyword


Let's understand the problem if we don't use this keyword by the
example given below:
class Student{  
int rollno;  
String name;  
float fee;  
Student(int rollno,String name,float fee){  
rollno=rollno;  
name=name;  
fee=fee;  
}  
void display()
{System.out.println(rollno+" "+name+" "+fee);}  

}  
class TestThis1{  
public static void main(String args[])
{  
Student s1=new Student(111,"ankit",5000f);  
Student s2=new Student(112,"sumit",6000f);  
s1.display();  
s2.display();  
}}  

O/P
0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance


variables are same. So, we are using this keyword to distinguish local
variable and instance variable.

Solution of the above problem by this keyword

class Student{  
int rollno;  
String name;  
float fee;  
Student(int rollno,String name,float fee){  
this.rollno=rollno;  
this.name=name;  
this.fee=fee;  
}  
void display(){System.out.println(rollno+" "+name+" "+fee);}  
}  
  
class TestThis2{  
public static void main(String args[]){  
Student s1=new Student(111,"ankit",5000f);  
Student s2=new Student(112,"sumit",6000f);  
s1.display();  
s2.display();  
}}  

O/P
111 ankit 5000
112 sumit 6000

If local variables(formal arguments) and instance variables are different,


there is no need to use this keyword like in the following program:

Program where this keyword is not required

class Student{  
int rollno;  
String name;  
float fee;  
Student(int r,String n,float f){  
rollno=r;  
name=n;  
fee=f;  
}  
void display(){System.out.println(rollno+" "+name+" "+fee);}  
}  
  
class TestThis3{  
public static void main(String args[]){  
Student s1=new Student(111,"ankit",5000f);  
Student s2=new Student(112,"sumit",6000f);  
s1.display();  
s2.display();  
}}  

O/P
111 ankit 5000
112 sumit 6000
Java Inner Classes
In Java, it is also possible to nest classes (a class within a class). The purpose of nested classes is to group classes that belong together,
which makes your code more readable and maintainable.

To access the inner class, create an object of the outer class, and then create an object of the inner class:

Example

class OuterClass {

int x = 10;

class InnerClass {

int y = 5;

public class MyMainClass {

public static void main(String[] args) {

OuterClass myOuter = new OuterClass();

OuterClass.InnerClass myInner = myOuter.new InnerClass();

System.out.println(myInner.y + myOuter.x);

// Outputs 15 (5 + 10)
Private Inner Class
Unlike a "regular" class, an inner class can be private or protected. If you
don't want outside objects to access the inner class, declare the class
as private:

Example

class OuterClass {

int x = 10;

private class InnerClass {

int y = 5;

public class MyMainClass {

public static void main(String[] args) {

OuterClass myOuter = new OuterClass();

OuterClass.InnerClass myInner = myOuter.new InnerClass();

System.out.println(myInner.y + myOuter.x);

If you try to access a private inner class from an outside class (MyMainClass), an error occurs

MyMainClass.java:12: error: OuterClass.InnerClass has private access in OuterClass


    OuterClass.InnerClass myInner = myOuter.new InnerClass();

Static Inner Class


An inner class can also be static, which means that you can access it without creating an object of the outer class:
Example

class OuterClass {

int x = 10;

static class InnerClass {

int y = 5;

public class MyMainClass {

public static void main(String[] args) {

OuterClass.InnerClass myInner = new OuterClass.InnerClass();

System.out.println(myInner.y);

// Outputs 5

Note: just like static attributes and methods, a static inner class does not have access to members of the outer class.

Access Outer Class From Inner Class


One advantage of inner classes, is that they can access attributes and methods of the outer class:

Example

class OuterClass {

int x = 10;

class InnerClass {

public int myInnerMethod() {

return x;

}
public class MyMainClass {

public static void main(String[] args) {

OuterClass myOuter = new OuterClass();

OuterClass.InnerClass myInner = myOuter.new InnerClass();

System.out.println(myInner.myInnerMethod());

// Outputs 10

Java – static variable with example


A static variable is common to all the instances (or objects) of the class because it is a class level variable. In other words you can say that
only a single copy of static variable is created and shared among all the instances of the class. Memory allocation for such variables only
happens once when the class is loaded in the memory.
Like variables we can have static block, static method and static class, to read about them refer:

Example 2: Static Variable can be accessed directly in a static method


class JavaExample{
static int age;
static String name;
//This is a Static Method
static void disp(){
System.out.println("Age is: "+age);
System.out.println("Name is: "+name);
}
// This is also a static method
public static void main(String args[])
{
age = 30;
name = "Steve";
disp();
}
}
Output:

Age is: 30
Name is: Steve

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Java static keyword


The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes.
The static keyword belongs to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class
Java static variable
5. If you declare any variable as static, it is known as a static variable.
6. The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
7. The static variable gets memory only once in the class area at the time of class loading.

Example of static variable


1. //Java Program to demonstrate the use of static variable  
2. class Student{  
3.    int rollno;//instance variable  
4.    String name;  
5.    static String college ="ITS";//static variable  
6.    //constructor  
7.    Student(int r, String n){  
8.    rollno = r;  
9.    name = n;  
10.    }  
11.    //method to display the values  
12.    void display (){System.out.println(rollno+" "+name+" "+college);}  
13. }  
14. //Test class to show the values of objects  
15. public class TestStaticVariable1{  
16.  public static void main(String args[]){  
17.  Student s1 = new Student(111,"Karan");  
18.  Student s2 = new Student(222,"Aryan");  
19.  //we can change the college of all objects by the single line of code  
20.  //Student.college="BBDIT";  
21.  s1.display();  
22.  s2.display();  
23.  }  
24. }  

O/P
111 Karan ITS
222 Aryan ITS

You might also like