Tag Archives: Java Classes and Object

Java Classes and Objects – Tutorial 2

1. Creating Objects.

2. Creating Class in the same File.

3. Default value of the Class instance variable and Local variable.

Code:

/*

Student Class

*/

public class Student {

private int id;
private String name;

public void setData(int tid,String tname)
{
id=tid;
name=tname;
}

public void display()
{
int testing=0;

System.out.println(“\n ID is:”+id);
System.out.println(“\n Name is:”+name);

System.out.println(testing);     //Not allowed without initialization
}
}

/*

Employee Class

*/
class Employee {

private int id;
private String name;

public void setData(int tid,String tname)
{
id=tid;
name=tname;
}

public void display()
{
System.out.println(“\nEmployee ID is:”+id);
System.out.println(“\nEmpoyee Name is:”+name);
}
}

/*

MainClass Class

*/
public class MainClass {

public static void main(String args[])
{
//Student Class
Student stuobj1=new Student(); //[ID/Name]

stuobj1.setData(1, “Vinod Pillai”);
stuobj1.display();

Student stuobj2;    //Reference created.

stuobj2=new Student(); //Memory is allocated now. [ID/Name]
stuobj2.display();        //Default values.
stuobj2.setData(2, “Vinod”);
stuobj2.display();

//Employee Class
Employee eobj=new Employee();
eobj.setData(1, “AbcXyz”);
eobj.display();
}
}

http://www.youtube.com/vinodthebest

Advertisements

Leave a comment

Filed under Java