Tuesday, July 17, 2012

Classes in Java

In object oriented programming class is struct. It is used to make object or instances of some kind. For example if you have a class having the name "Car", then it will create cars as its objects or instances. In simple word class in factory which makes objects. Class itself can't be used in programming without creating its objects. We create objects and use them in our programs. For example if we have a program that calculates the grades of the student. It takes marks achieved by them and give some grade as its output. We have written a class named "Student". Then we will create the objects of this class and every object is assigned unique attributes or properties. So lets see an example of class to understand it.

public class Student {


}

This is very simple way of using classes in your programs. Now we have a class it will create object having no properties and operations. So now we will define the properties of this class. Think about the properties a student can have....There are lot of things a students can have like name, roll No or ID, father name, address, class or year,grades, fee, number of sisters and brother and many more things. But we will use only marks and grades so we will not touch other things. See the code below.


public class Student {
private int totalMarks;
private int totalSubjects;
private int average;
private String grade;
}

Now we have defined the required properties of the student. Now we define methods or functions of the class to use these properties.

public class Student {
private int totalMarks;
private int totalSubjects;
private int percentage;
private String grade;

public void calculateAverage()
{
percentage = totalMarks/totalSubjects;
}

public void display()
{
System.out,println(totalMarks);
System.out,println(totalSubjects);
System.out,println(average);
System.out,println(grade);
}
}

Now we have two methods of the class and can use them to perform our task. Of course there can be many other methods of the class but to keep it simple i have just defined two. Now we will use this class in our main program.

public class StudentTest{

public static void main(Stirng[] Args)
{
Student s1 = new Student();
Student s2 = new Student();
s1.display();
s2.display();
}
}

s1 and s2 is the object or variable of this class. They are separate students and can have different properties or values of its variables.
So that was the today's lesson. Hopefully you have enjoyed it. Please do lot of practice of this lesson because class is the most important or key element in object oriented programming. So its time say good bye. Stay with us..........

No comments:

Post a Comment