4 Classes and Methods




Class
Classes represents real world entities like flower, vehicle, bank account etc.  Hence the class represents the attributes and behavior of the entity.  These attributes are known as data and the behavior is known as method. 

Thus the class can be defined as a collection of data and methods (methods act on the data).  So data and methods are the wrapped into a single entity called as a class.  Classes are also called as templates because they provide basic framework of an object.  The class does not hold any value and until it is used for object creation.  When class template is ready, it is used to create instances or objects.  Class are fundamentals of Java language.

Example (Creating an object from the class)
class Fruit{
int seeds;
String category;
float price;
public void ShowWhat( ){
System.out.println("\n\n This is an Orange" +"\n");
}
public void PutData(int s, String c, float p){
seeds    = s;
category = c;
price    = p;
}
public void ShowData( )
{
System.out.println("Number of Seeds = " + seeds);
System.out.println("Category =" + category);
System.out.println("Price ="+price+"Per Piece" +"\n");
            }
}
class FruitClass{
public static void main(String [] args) {
Fruit Orange = new Fruit( );
Orange.ShowWhat( );
Orange.PutData(7,"Citrus",1.50F);
Orange.ShowData( );
            }
}

In the above example a class called fruit is created.  It contains properties of fruits and methods to access those properties.  These properties are implemented with built in data types.  When a class is declared, it becomes abstract data type.   This data type is used to create objects of that class.

In the above example the statement Fruit Orange is creates the new object for Fruit class with the keyword new.  We can create n number of objects from a class.  But one object can be different from another object because values of member variables of each object are different.  Objects share the methods but they have different copies of attributes or properties.

Example ( Creating Multiple Objects)
class Fruit{
boolean seedless;
boolean seasonal;
float price;
void setProperties(boolean seed,boolean season, float p){
seedless=seed;
seasonal=season;
price=p;
}
void printProperties( )
{
System.out.println("Following are properties of Fruit ");
if(seedless)
System.out.println("Fruit is seedless");
else
System.out.println("Fruit is seeded");
if(seasonal)
System.out.println("Fruit is seasonal");
else
System.out.println("Fruit is not seasonal");
System.out.println("Fruit's Price  "+price );
}
}
class Fruits1{
public static void main(String [] args)
{
        Fruit f1,f2,f3;
        f1 = new Fruit( );
        f2 = new Fruit( );
        f3 = new Fruit( );
        f1.setProperties(true,false,50.0F);
        f2.setProperties(false,false,50.0F);
        f3.setProperties(false,true,50.0F);
        f1.printProperties( );
            }
}

Inheritance in Java
Inheritance is nothing but acquiring properties of another entity or class.  Inheritance in Java is implemented by superclass and subclass relationship.  Superclass is inherited class and the subclass inherits the super class.   When inheritance is implemented, subclass gets properties of superclass plus its own properties.  For example consider a class “Vehicle” and class “Scooter”.  Properties of Vehicle class is speed, seating capacity and properties of Scooter class is petrol capacity, gear.  Scooter class is inherited from the Vehicle class.  Hence the Vehicle class is the Superclass and Scooter is the subclass.  Scooter class gets the properties (speed, seating capacity) of the Vehicle class, plus it has its own properties (petrol capacity, gear).  Thus subclass enjoys the properties of its own as well as of its superclass.  Following diagram illustrates this:-


Example (Inheritance Program)
class Employee{
String name;
char sex;
Employee(String n,char s){
name =n;
sex=s;
}
public String getName( ){
return name;
}
public char getSex( ){
return sex;
}
}
class Worker extends Employee{
char category;
boolean dressAllowance;
Worker(String n,char s,char c,boolean d){
super(n,s);
category =c;
dressAllowance =d;
}
public char getCategory( ){
return category;
}
public boolean getAll( ){
return dressAllowance;
}
}
class Officer extends Employee{
char EmpClass;
int Experiance;
boolean Vehicle;
Officer(String n,char s,char c,int e, boolean v){
super(n,s);
EmpClass=c;
Experiance=e;
Vehicle=v;
}
public char getEmpClass( ){
return EmpClass;
}
public int getExp( ){
return Experiance;
}
public boolean getVehicle( ){
return Vehicle;
}
}
class InheDemo{
public static void main(String args[]){
Worker w = new Worker("M.John",'M','B',true);
System.out.println("Worker Information ");
System.out.println("Name        :"+w.getName( ));
System.out.println("Gender     :"+w.getSex( ));
System.out.println("Category   :"+w.getCategory( ));
if(w.getAll( ))
System.out.println("Dress Allowance is paid ");
else
System.out.println("Dress Allowance is not paid ");
Officer O = new Officer("S.David",'F','I',15,true);
System.out.println("Officer Information ");
System.out.println("Name        :"+O.getName( ));
System.out.println("Gender     :"+O.getSex( ));
System.out.println("Class        :"+O.getEmpClass( ));
System.out.println("Experiance      :"+O.getExp( )+"years");
if (O.getVehicle( ))
System.out.println("Vehicle is provided" );
else
System.out.println("Vehicle is Not provided" );
}
}

Constructor
Constructor is a special method that does not have return type and has same name that of the class name.  It means constructor can act as a normal method of function but it can not return any value.  Basically, constructor is defined for every class to initialize its member variables.  The constructor method of a class is automatically called when we create object of that class.  We can pass values to constructor members also.  The constructor method constructs the object by initializing member variables and creating environment for the object.

Hence whenever an object is created its constructor methods is called.  If class does not have any constructor method compiler provides default constructor to that class.  But it does not set parameters for working of an object like size in case of object of type name.  Thus when an object is created for a class, if there is no constructor method defined in the class, then the default constructor method is automatically called, which assigns the initial values to the variable members.

Example (Constructor program)
class Fruits{
int seeds;
String category;
float price;
public Fruits( ){
            seeds    = 5;
            category = "Citrus";
            price    = 2.75F;
                        }
public void ShowData( ){
System.out.println("Number of Seeds = " + seeds);
System.out.println("Category =" + category);
System.out.println("Price = "+ price + "Per Piece" +"\n");
            }
}  //Constructor programme
class FruitClass1{
public static void main(String [] args)
            {
            Fruits Orange = new Fruits( );
            Orange.ShowData( );
            }
}

Methods
A method is nothing but a set of executable statements.  Methods are also interface to the data of the object.  Methods also help to provide a structured approach to programming.  A program can be divided into different methods, which is nothing but logical grouping of related executable statements.  Methods are also called as functions.

Advantages
  • Methods are provided to give access to the data of the class.  No one can directly deal with the data of the object.  Access to the data is only through methods.
  • A program can be divided logically.
  • No need to repeat the same set of statements again and again as separate method can be declared which will be called as and when required.
  • Programs become easy to debug.
There are two types of methods namely overloaded methods and overridden methods.  Overloaded methods are in the same class and have same name but different parameter lists.  Overridden methods are in superclass as well as in the subclass.

Polymorphism
Is taking different form at different time or behaving differently depending upon the environment.

Practical Examples

Example 1
class MyFruit
{
boolean seedless;
boolean seasonal;
float price;
void setProperties(boolean seed,boolean season,float p)
{
seedless =seed;
seasonal =season;
price =p;
}
void printProperties( )
{
System.out.println("Following are proeprties of Fruit");
if(seedless)
System.out.println("Fruit is Seedless");
else
System.out.println("Fruit is Seeded");
if(seasonal)
System.out.println("Fruit is Seasonal");
else
System.out.println("Fruit is not Seasonal");
System.out.println("Price "+price);
}
}
class FruitDemo{
public static void main(String args[])
{
MyFruit f1,f2,f3;
f1= new MyFruit( );
f2= new MyFruit( );
f3= new MyFruit( );
f1.setProperties(true,false,50.0F);
f2.setProperties(false,false,20.0F);
f3.setProperties(false,true,50.0F);
f1.printProperties( );
f2.printProperties( );
f3.printProperties( );
}
}

Example 2
class Calculation
{
public void add(int a,int b){
int c= a+b;
System.out.println("Addition of two integer numbers is " +c);
}

public void add(float a,float b)
{
float c = a+b;
System.out.println("Addition of two float numbers is " +c);
}
public void add(String a,String b)
{
String c = a+b;
System.out.println("Addition of two strings is " +c);
}
}
class CalculationDemo
{
public static void main(String args[])
{
Calculation c = new Calculation( );
c.add(10,20);
c.add(45.5F,35.65F);
c.add("Good","Morning");
}
}

Example 3
class SuperClass
{
int a;
SuperClass( )
{
a =10;
}
public void printA( )
{
System.out.println("In the Super Class");
System.out.println("Value of a "+a);
}
}
class SubClass extends SuperClass {
int a;
SubClass(int a)
{
this.a =a;
}
public void printA( )
{
System.out.println("In the Sub Class");
System.out.println("Value of a "+a);
}
}
class OverRideDemo {
public static void main(String args[]){

SuperClass s1 = new SubClass(10);
s1.printA( );
SubClass s2 = new SubClass(20);
s2.printA( );
}
}

Example 4
class OuterClass {
String str;
boolean OuterClassAccessible;
InnerClass in;
public OuterClass( ) {
str = new String("Outer Class Variable");
OuterClassAccessible=true;
OuterClass.InnerClass in = new OuterClass.InnerClass( );
System.out.println(str);
System.out.println("OuterClassAccessible :"+OuterClassAccessible);
System.out.println("InnerClassAccessible :"+in.InnerClassAccessible);
}
class InnerClass {
String str;
boolean InnerClassAccessible;
public InnerClass( ) {
str = new String("Inner Class Variable");
InnerClassAccessible=true;
System.out.println(str);
System.out.println("InnerClassAccessible :"+InnerClassAccessible);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
OuterClass out = new OuterClass( );
}
}

No comments:

Post a Comment