Java Tutorial:Class Fundamentals and Object Creation



A class facilitates information hiding, security, and modularity. Classes are used to define a new data type. You can use the created data type for solving programs. We can say that class is a template for an object of the properties and object is an instance of a class. Before defining a class you must have enough idea about how does it work.

Syntax of Java Class Definition
class className
{
type instance_variable1;
type instance_variable2;
type instance_variable3;
type instance_variableN;
type method_name1(arguments)
{
//body of the method1
}
type method_name2(arguments)
{
//body of the method2;
}
type method_nameN(arguments)
{
//body of the methodN;
}
}
If you observe the above program, class is declared using class keyword. Data and methods are defined within the class. Each variable has type and name. Here data are called member data or instance variable of the class,  methods are called member function of the class.

It's time to start experiment with class



class Student
{
int roll;
String name;
void student_info()
{
System.out.println("Student name :"+name);
System.out.println("Student roll :"+roll);
}
}
class Student_Class
{
public static void main(String[] args)
{
Student obj1=new Student();
obj1.roll=12;
obj1.name="John";
obj1.student_info();
Student obj2=new Student();
obj2.roll=13;
obj2.name="Nikisurf";
obj2.student_info();
obj1.name="Don Wiki";
obj1.student_info();
}
}

_

As I mentioned earlier class defines a new data type. Here Student is new Data type. We can create objects as below:

Student obj1=new Student();

Object of a class has its own copy of data members defined in the class. But member functions have only one copy and shared by all object of that class.

Creating Objects

Object creation is very simple task,. We need to allocate memory for an object. It is done by new operator. It helps to create memory dynamically. Reference to object means address of object. How to create a reference to object in Java? Consider the above example,

Student obj1;
// Here declaring reference to Object.
Next our job is to allocate memory for an object.
obj1=new Student();
We can simplify the above statements as single statement.
Student obj1=new Student(); // it looks great!

Student obj2=new Student();
obj2.roll=28;
obj2.student_info();

//You can also assign object reference to variables; one object can be assigned to another one.
Java Object Reference 

class Foo
{
int roll;
String name;
void info()
{
System.out.println("Student name :"+name);
System.out.println("Student roll :"+roll);
}
}
class Ref_Class
{
public static void main(String[] args)
{
Foo f=new Foo();
Foo g=new Foo();
f.roll=10;
f.name="Nikisurf";
f.info();
g=f;

g.roll=11;
g.name="Sujith";
g.info();

}
}
Java Tutorial:Class Fundamentals and Object Creation Java Tutorial:Class Fundamentals and Object Creation Reviewed by Nikin on 06 January Rating: 5
Powered by Blogger.