xxxxxxxxxx
It is a basic unit of Object-Oriented Programming and represents real life
entities. A typical Java program creates many objects, which as you know,
interact by invoking methods. An object consists of :
State: It is represented by attributes of an object. It also reflects the
properties of an object.
Behavior: It is represented by methods of an object. It also reflects the
response of an object with other objects.
Identity: It gives a unique name to an object and enables one object to
interact with other objects.
class Student
{
int id;//data member (also instance variable)
String name; //data member (also instance variable)
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
xxxxxxxxxx
Remember from the Java Syntax chapter
that a class should always start with an uppercase first letter,
and that the name of the java file should match the class name.
xxxxxxxxxx
ClassName obj = new ClassName(); //creating an object of ClassName class
System.out.println(obj.field1); // calling field of the object (bad practice, make the fields private)
System.out.println(obj.field2);
obj.doSomething(); // calling method of the object
xxxxxxxxxx
// Default behavior of toString() is to print class name, then
// @, then unsigned hexadecimal representation of the hash code
// of the object
public String toString()
{
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
xxxxxxxxxx
The Object class is the parent class of all the classes in java by default.In
other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you
dont know. Notice that parent class reference variable can refer the child
class object, know as upcasting.
xxxxxxxxxx
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
xxxxxxxxxx
Using new keyword.
Using new instance.
Using clone() method.
Using deserialization.
Using newInstance() method of Constructor class.