6 Java Classes
6 Java Classes
Java objects
Java objects
An object has three characteristics:
•State: represents the data (value) of
an object.
•Behavior: represents the behavior
(functionality) of an object such as
deposit, withdraw, etc.
•Identity: An object identity is typically
implemented via a unique ID. The
value of the ID is not visible to the
external user. However, it is used
internally by the JVM to identify each
object uniquely.
Java objects
• Java is an object-oriented programming language.
• The car has attributes, such as weight and color, and methods, such as drive and
brake.
• It contains all the details about the floors, doors, windows, etc.
// fields
// methods
• Fields
• Methods
• Constructors
• Blocks
class Bicycle {
// state or field
int gear = 5;
// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}
Java Objects
• An object is called an instance of a class.
• The new is a keyword which is used to allocate memory for the object.
Example: Creating a Class and its object
public class Student{
String name;
int rollno;
int age;
void info(){
System.out.println("Name: "+name);
System.out.println("Roll Number: "+rollno);
System.out.println("Age: "+age);
}
public static void main(String[] args) {
Student student = new Student();
// Calling method
student.info();
} }
Output:
Name: Ramesh
Age: 25
3 ways to initialize object
There are 3 ways to initialize object in Java.
• By reference variable
• By method
• By constructor
1) Object and Class Example: Initialization through reference
• 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();
}
}
• 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 a constructor
• By new keyword
• By newInstance() method
• By clone() method
• By deserialization