Object in Java - State and Behaviour Explained
Object
- Object is a real-world entity.
- Object contains two things:
i. State
ii. Behaviour
i. State
- State can change.
- State is also called attributes or variables.
- State is used to represent type of data or state of an Object.
For Example:
- Student is an Object where
rollis a state and roll type isint. - Student is an Object where
nameis a state and name type isString. - Student is an Object where
marksis a state and marks type isfloat.
ii. Behaviour
- Behaviour of an Object never changes (method definition remains same).
- Behaviour is represented as a method.
For Example:
- Student is an Object where
study()orlearn()is a behaviour. - Pen is an Object where
write()is a behaviour. - AC is an Object where
on(), off(), swing()etc. are behaviours.
Object Example - Practical Code
// This is a template or blueprint of an Object.
// This class contains information about Student.
// But you don't know the state of student, that's why this type of class is called Template or Blueprint.
class Student {
String name;
int roll;
}
// This class is used for testing.
class Test {
// This is an entry point from where your program starts.
public static void main(String[] args) {
// This is an object or instance
// This object initializes the state with default values.
// new is an operator/keyword used to create blank/new memory.
// Student() is a constructor which initializes the values.
// After completion it returns same type of address where data is allocated.
// std works as a reference variable who points to address of default values.
Student std = new Student();
// If you want to change default values to actual values:
std.name = "suresh singh";
std.roll = 123;
// To access data from that location:
System.out.println(std.name);
System.out.println(std.roll);
}
}
Output is:
suresh singh
123
123
Conclusion
Object is an instance of class that has state (variables) and behaviour (methods). Class is blueprint, object is real entity created using new keyword. Understanding state and behaviour is foundation of OOP.
Next: Class vs Object, Constructor in Java, new keyword
No comments:
Post a Comment