Wednesday, January 19, 2011

JAVA Programming : Class

JAVA Class


Class in Java is a template that describes the kind of state and behavior that objects of its type support. In simple words a Class is an blueprint from which an object is constructed. 
For Example think of a Blueprint of a house. A class for an object is like a blueprint for a house. A blueprint can be used to build a lot of hoses and a class can be used to build a lot of object.
Things defines inside the class are said to be member of the class and when the objects are constructed from the class, the member of class also become member of each object. 

A Class declaration can be done in this way:


public class Television {

    // the Television class has two fields
    public int size;
    public String  colorType;

    // the Television class has one constructor
    public Television(int tvSize, String tvColorType) {                      


        size = tvSize;
        colorType = tvColorType;
    }

    // the Television class has two methods
    public void setSize(int newValue) {

        size = newValue;
    }


    public void setColorType(String newValue) {

        colorType = newValue;
    }
}



Java Subclass :
Subclass in Java is a class that is an extension of an existing class. In other words Subclass is a class that extends another class. A Subclass is also known as Derived Class or Child Class.
A Subclass will inherits all properties like variables and methods of Extended Class or Super Class.
For example, we make a Class LcdTv which extends the class Television. Now the LcdTv class will have all the properties of Television so we don't need to write them again but LcdTv class has one extra property contrastRatio that is not present in Television Class, so we need to declare that field in LcdTv class.


public class LcdTv extends Television {
  
    // the LcdTv subclass has one field
    public String contrastRatio;

    // the LcdTv subclass has one constructor
    public LcdTv(int tvSize, String tvColorType, String tvContrastRatio) {   

        super(tvSize, tvColorType);
        contrastRatio = tvContrastRatio;
    }  

    // the LcdTv subclass has one method
    public void setHeight(String newValue) {

        contrastRatio = newValue;
    }  

}


No comments:

Post a Comment