Note

If you cannot find what you are looking for. Please visit our sitemap

Sunday, 22 February 2015

Java Class Class Fundamentals

                        Java Class Class Fundamentals

Class is at the core of java. It is the logical construct upon which the entire java language is built because it defines the shape and nature of an object. It is the basis of Object Oriented Programming (OOP).

The General Form of a Class:

When you define a class, you declare its exact form and nature. You do this by specifying the data that it contains and the code that operates on that data. While very simple classes may contain only code or data, most real-world classes contain both.
A class is declared by one of the class keyword. The general form of a class is described below:

class classname {
type instance-var1;
type instance-var2;
//...
type instane-varn;

type methodname1 (parameter-list){
         // body of method
}
 type methodname2 (parameter-list){
         //
 type methodnamen (parameter-list){

}

}

The data, or variable, defined within a class are called instance variable. The code is contained within methods. The methods and variable are defined within a class are called members of the class. The instance variable are acted upon and accessed by the method defined for that class.Method determines how a class data can be used.

A Simple Class:

Here is a class called rectangle the defines two instance variable: width and height.

class rectangle {
   double width;
   double length;
}

Class declaration only declares a template. It does not create an actual object. To create a rectangle object, you will use statement like stated below:

rectangle  myrectangle = new rectangle ();

After this statement executes, myrectangle will be an instance of rectangle.
Thus, every rectangle object will contain its own copies of the instance variables width and length. To access these variables, you will use dot (.) operator. The dot operator links the name of the object with the name of the instance variable.

For exp, to assign the width variable of myrectangle the value of 100, you would use the following statement:

myrectangle.width = 100;

Here is a program  that uses class rectangle and compute area of rectangle:

/*
         This is a Java Program that uses class rectangle.
          Program developed by #Asad Hussain
         This file name is "rectanglearea.java".
*/
import java.util.*;
class rectangle {
  double length;
  double width;

}
public class rectanglearea {
    public static void main(String args[]){

        rectangle myrectangle = new rectangle();
        double area;

        myrectangle.width = 10;
        myrectangle.length = 15;

        area = myrectangle.width * myrectangle.length;

        System.out.println("Area is " + area);
   
}
}

Output of this Program:

Java Program that uses class rectangle to compute area by Asad Hussain

 

Written By : Asad Hussain

No comments:

Post a Comment