Professional Documents
Culture Documents
Skill Programming EXPT 3
Skill Programming EXPT 3
Skill Programming EXPT 3
:3
Aim: Write Java Program on class and object
Objectives:-Student/we will learn to define class, and create the object of the class.
.
Theory:
In this program we are using the concept of class and object . So we are seeing these
concepts in detail here.
Defining a Class:
A class is a user defined data type with template that serves to define its properties. Once the
class has been defined, we can create “variables” of that type using declarations that are similar
to the basic type declarations.
Class classname
{
[fields declarations;]
[method declarations;]
}
}
Remember these variables are only declared and therefore no storage space has been created in
the memory. Instance variables are also known as member variables.
Method Declaration:
The methods are declared inside the body of the class but immediately after the declaration of
instance variables. The general form of method declaration is: type method name (parameter-
list)
{
Method-body;
}
Accessing Class Members:
As we have created objects each containing its own set of variables, we should assign values to
these variables in order to use them in program.
All variables must be assigned values before they are used. We must use the concerned object
and the dot operator as shown below:
objectname.variablename = value;
objectname.methodname(parameter-list);
Algorithm:
Step 1: Start
Step 3: In class student , Declare roll no of type int and name of type string
Step 4: define methods insertdata(int r,String n) and getdata() to get roll no and name for
objects of student class.
Step 5: define method display() to display roll no and name of objects of student class.
Step 6: define main method class studentmain in which create objects s1 and s2
of class student
Step 7: call insertdata() method to get roll no and name for s1 and call getdata()
Step 8: call display() method to display roll no and name for s1 and s2.
Step 9: stop.
Program(Code):
import java.io.*;
class Student
{
int rollno;
String name;
void displayInformation()
{
System.out.println(rollno+" "+name);
}
}
class studentmain
{
public static void main(String args[])throws Exception
{
Student s1=new Student();
Student s2=new Student();
s1.insertdata(1,"Sachin");
s2.getdata();
s1.displayInformation();
s2.displayInformation();
}
}
Output:
C:\>
C:\>d:
D:\>cd programs
D:\programs>path="C:\jdk1.6.0_23\bin";
D:\programs>javac studentmain.java
Note: studentmain.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
D:\programs>java studentmain
Enter roll no
2
name
ravi
1 Sachin
2 ravi
Outcome: with this we/student will able to use userdefined class and object in the java program.