Explain Class Object Member variable and Methods in java


Class
A class is the blueprint in which a template can be formed, in real word scenario assume we need to store an employee record.  Here Employee becomes the class.

Member variable
Member variables in a class?these are called fields. Member variable become the place to hold all necessary information about the class.

Example
public class Employee
{
String name;
int age;
long ph:
String email;
}
Save this file as Employee.java. wait for another example to run this.

Objects
Objects or we called it as an instance that are created based on class and holds the copy of member variable and methods. In the following figure e1, e2, e3 are called as Objects, 
Syntax for creating Object : Employee e1=new Employee();


Example
public class Main
{
public static void main(String[] args)
{
Employee e1=new Employee();
e1.name="raja";
e1.age=20;
e1.ph=632736l;
e1.email=z@g.com
System.out.println(e1.name);
System.out.println(e1.age);
System.out.println(e1.ph);
System.out.println(e1.email);

}
}
Save this file as Main.java along with Employee.java. Now compile and run Employee.java.

Methods
Methods add behavior to our class or helps us to write reusable code. Example calculating salary, printing employee information etc for our Employee class.
Example:
public class Employee
{
String name;
int age;
long ph:
String email;
void setData(String n, int a, long p, String e)
{
name=n;
age=a;
ph=p;
email=e;
}
void display()
{
System.out.println(name);
System.out.println(age);
System.out.println(ph);
System.out.println(email);
}
}
public class Main
{
public static void main(String[] args)
{
Employee e1=new Employee();
e1.setData("raja",22,64564l,"z@g.com");
e1.display();
}
}



Comments


©candidjava.com