Thursday, March 11, 2010

Functions: Class, Instance and Constructor

testparent.java
public class testparent
{
public static void main(String[] args)
{
parent.hello();                     // 3. class function
parent p1 = new parent();           // 1. constructor function
p1.display();                       // 2. instance function
parent p2 = new parent("ALICE");    // 1. overload constructor function
p2.display();                       // 2. instance function
p1.display();                       // 2. instance function
}
}

parent.java => super class
public class parent
{
  // Data Members --------------------------------------------------------------
String name;          // 1. instance variable go to each instance created
static int total = 0; // 2. class variable shared by all

// Function Members -------------------------------------------------------- 
     // 1. Constructor Functions
     //-------------------------
parent()                //parent p1 = new parent(); has same name
{
name = " ";
total++;
}
------------------------------------------------------------------
parent(String n)        //parent p2 = new parent("some string"); w/arguments
{                     //this is an overload construction function
name = n;
total ++;
}
     // 2. Instance Function
     //---------------------
public void display()
{
System.out.printf("TOTAL %d NAME: %s \n", total, name );
}

     // 3. Class Function
     //---------------------
static public void hello()
{
System.out.printf("HELLO.Welcome.\n");        
}
}


No comments:

Post a Comment