HOME
J2ee tutorials
Java introduction
Java basic
Java installation
Java Packages Learn
Applets Java Threads Java Gui component
 Java Event Handaling Java Streams and Files
 Java Swings Java JDBC
 Java Network Programming Java RMI
 Java Servlets Java javabeans
 EJB Struts

|
Objects
Before the development of object oriented programming, the variables were considered as isolated entities. For example suppose a program needs to handle data relegated to a student, say the students roll numbers, his marks and grade. Three separate variable will be declared for this.
int rollnumber, marks;
Char grade;
These two statements do two things
- it says that the variable roll number and marks are integers and grade is character variable.
-
It also allocates storage for these variables
This approach as 2 disadvantage
- if the program needs to keep track of various students records,. There will be more declarations that would be needed for each student. For example
int rollnumber1,marks1;
Char grad1;
int rollnumber2,marks2;
Char grade2;
this approach can become very cumbersome
- the other drawback is that this approach completely ignores that fact that the three variables rollnumber, marks and grade are related and are a data associated with a single student.
in order to address these to drawbacks java uses the class to create new types. For example to define a type that represents a student, we need storage space for 2 integers and a char,
This is defined as follows
Class student
{
int rollnumbers;
int marks;
char grade;
}
a variable can be declared as type student as follows;
student s1,s2;
The members variable of this class ( rollnumber ,marks and grade) can be accessed using the dot(.) operator for example
s1.rollnumber=9;
s1.marks=90;
s1.grade=’a’;
s2.rollnumber=23;
s2.marks=60;
s2.grade=’b’;
example using object
let us now write a example that creates an object of the class student and display the roll number,marks and grade of astudent
|
class student
{
int rollnumber;
int marks;
char grade;
void printrollno()
{
System.out.println("rollnumber= " + rollnumber);
}
void printmarks()
{
System.out.println("marks=" + marks);
}
void printGrade()
{
System.out.println("grade =" +grade);
}
}
public class objectexample
{
public static void main(String str[])
{
student s1;
s1=new student();
s1.rollnumber=9;
s1.marks=90;
s1.grade='a';
s1.printrollno();
s1.printmarks();
s1.printgrade();
}
}
|
|
|