Class Fundamentals

            A class is a template for an object, and an object is an instance of a class. Because an object is an instance of a class, we will often see the two words object and instance used interchangeably

 

The General Form of a Class

A class is declared by use of the class keyword

class classname

 {

Type instance-variable1;

type instance-variable2;

// ...

type instance-variableN;

 

type methodname1(parameter-list)

{

// body of method

  }

 type methodname2(parameter-list)

 {

// body of method

   }

// ...

type methodnameN(parameter-list)

{

            // body of method

   }

}

 

The data, or variables, defined within a class are called instance variables.The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class.All methods have the same general form as main( )

A Simple Class

/* A program that uses the Box class. Call this file BoxDemo.java */

 class Box

{

double width;

double height;

double depth;

 }

 // This class declares an object of type Box. class BoxDemo

class BoxDemo

{

      public static void main(String args[])

{

                  Box mybox = new Box();

double vol; // assign values to mybox's instance variables

                  mybox.width = 10;

                  mybox.height = 20;

                  mybox.depth = 15;

 // compute volume of box

vol = mybox.width * mybox.height * mybox.depth; 

System.out.println("Volume is " + vol);

}

 }

 

Declaring Objects

  •        1st, you must declare a variable of the class type.
  •          2nd, you must acquire an actual, physical copy of the object and assign it to that variable- can do this using the new operator. The new operator dynamically allocates memory for an object and returns a reference to it
  •          declare an object of type Box:  -->  Box mybox;
  •          allocate a Box object               :-->   mybox = new Box();            

program declares two Box objects

// This program declares two Box objects.

class Box

 {

double width,height,depth;

}

class BoxDemo

{

public static void main(String args[])

{

 Box mybox1 = new Box();

 Box mybox2 = new Box();

 double vol;

// assign values to mybox1's instance variables

 mybox1.width = 10;

mybox1.height = 20;

mybox1.depth = 15;

/* assign different values to mybox2's instance variables */

mybox2.width = 3;

mybox2.height = 6;

 mybox2.depth = 9;

// compute volume of first box

vol = mybox1.width * mybox1.height * mybox1.depth;

System.out.println("Volume is " + vol);

// compute volume of second box

vol = mybox2.width * mybox2.height * mybox2.depth;

System.out.println("Volume is " + vol);

 }

 }

Output:

Volume is 3000.0

Volume is 162.0

 

Declaring Objects

Box mybox = new Box()

Box mybox;                      // declare reference to object

mybox = new Box();       // allocate a Box object












 Constructors

A constructor initializes an object immediately upon creation.It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes.they have no return type, not even void.

Program

/* Here, Box uses a constructor to initialize the dimensions of a box. */

 class Box

{

      double width, height,depth;

// This is the constructor for Box.

Box( )

{

             System.out.println("Constructing Box");

            width = 10, height = 10, depth = 10;

 }

 // compute and return volume

      double volume()

{

            return width * height * depth;

}

 }

 class BoxDemo

{

            public static void main(String args[])

{

                        // declare, allocate, and initialize Box objects

            Box mybox1 = new Box();

            Box mybox2 = new Box();

            double vol;

                        // get volume of first box

            vol = mybox1.volume();

             System.out.println("Volume is " + vol);

                        // get volume of second box

            vol = mybox2.volume();

 System.out.println("Volume is " + vol);

}

}

When this program is run, it generates the following results:

Constructing Box

 Constructing Box

Volume is 1000.0

Volume is 1000.0

 

 

Parameterized Constructors

Program

/* Here, Box uses a parameterized constructor to initialize the dimensions of a box. */

 class Box

{

            double width,height,depth;

            // This is the constructor for Box.

             Box(double w, double h, double d)

{

             width = w; height = h; depth = d;

             }

            // compute and return volume

            double volume()

{

                        return width * height * depth;

                        }

 }

 class BoxDemo

{

            public static void main(String args[])

{

                        // declare, allocate, and initialize Box objects

            Box mybox1 = new Box(10, 20, 15);

            Box mybox2 = new Box(3, 6, 9);

            double vol;

                        // get volume of first box

             vol = mybox1.volume();

            System.out.println("Volume is " + vol);

                        // get volume of second box

            vol = mybox2.volume();

            System.out.println("Volume is " + vol);

}

 }

The this Keyword

·         Sometimes a method will need to refer to the object that invoked it

·         Java defines the this keyword

·         this can be used inside any method to refer to the current object

// A redundant use of this.

 Box(double w, double h, double d)

 {

this.width = w;

this.height = h;

this.depth = d;

}

 

The finalize( ) Method

Sometimes an object will need to perform some action when it is destroyed. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls that method whenever it is about to recycle an object of that class. Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed

The finalize( ) method has this general form:

protected void finalize( )

 {

 // finalization code here

 }

Overloading Methods

In Java it is possible to define two or more methods within the same class with same name.When this is the case, the methods are said to be overloaded. and the process is referred to as method overloading.overloaded methods must differ in the type and/or number of their parameters. overloaded methods may have different return types

Demonstrating method overloading.

class OverloadDemo

{

 void test( )

 {

 System.out.println("No parameters");

}

// Overload test for one integer parameter.

            void test(int a)

 {

                        System.out.println("a: " + a);

 }

                        // Overload test for two integer parameters.

void test(int a, int b)

            {

                         System.out.println("a and b: " + a + " " + b);

            }

// overload test for a double parameter

double test(double a)

{

                         System.out.println("double a: " + a);

 return a*a;

}

 }

class Overload

{

public static void main(String args[])

{

OverloadDemo ob = new OverloadDemo();

double result;

                                    // call all versions of test()

ob.test();

ob.test(10);

ob.test(10, 20);

result = ob.test(123.25);

System.out.println("Result of ob.test(123.25): " + result);

}

}

This program generates the following output:

No parameters

a: 10 a and b: 10 20

double a: 123.25

Result of ob.test(123.25): 15190.5625

 

Overloading Constructors

class Box

{

 double width,height,depth;

// constructor used when all dimensions specified

            Box(double w, double h, double d)

{

 width = w; height = h; depth = d;

}

// constructor used when no dimensions specified

 Box()

{

width = -1; height = -1; depth = -1;

}

// constructor used when cube is created

            Box(double len)

 {

width = height = depth = len;

 }

// compute and return volume

double volume()

{

                        return width * height * depth;

 }

}

 

class OverloadCons

 {

            public static void main(String args[])

 {

// create boxes using the various constructors

Box mybox1 = new Box(10, 20, 15);

            Box mybox2 = new Box();

            Box mycube = new Box(7);

            double vol;

                        // get volume of first box

            vol = mybox1.volume();

System.out.println("Volume of mybox1 is " + vol);

// get volume of second box

 vol = mybox2.volume();

System.out.println("Volume of mybox2 is " + vol);

 // get volume of cube

 vol = mycube.volume();

System.out.println("Volume of mycube is " + vol);

 }

 }

The output produced by this program is shown here:

Volume of mybox1 is 3000.0

Volume of mybox2 is -1.0

Volume of mycube is 343.0

 

Static

There will be times when we may need to define a class member that will be used independently of any object of that class. Normally, a class member must be accessed only in conjunction with an object of its class.it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. The most common example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist.

Methods declared as static have several restrictions:

·         They can only call other static methods.

·         They must only access static data.

·         They cannot refer to this or super in any way

 

Demonstrate static variables, methods, and blocks

class UseStatic

 {

            static int a = 3;

            static int b;

 static void meth(int x)

 {

System.out.println("x = " + x);

System.out.println("a = " + a);

System.out.println("b = " + b);

}

Static

{

 System.out.println("Static block initialized.");

b = a * 4;

}

 public static void main(String args[])

 {

 meth(42);

}

 }

 

Here is the output of the program:

Static block initialized.

x = 42

a = 3

b = 12

 

Final

A variable can be declared as final.  Doing so prevents its contents from being modified. This means that we must initialize a final variable when it is declared

final int FILE_NEW = 1;

It is a common coding convention to choose all uppercase identifiers for final variables. a final variable is essentially a constant

Nested and Inner Classes

Defining a class within another class are known as nested classes.The scope of a nested class is bounded by the scope of its enclosing class.if class B is defined within class A, then B does not exist independently of A. A nested class has access to the members, including private members, of the class in which it is nested.the enclosing class does not have access to the members of the nested class

There are two types of nested classes:

·         static

·         and non-static.

A static nested class is one that has the static modifier applied.

Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used.

The most important type of nested class is the inner class.

An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do.

// Demonstrate an inner class.

class Outer

 {

       int outer_x = 100;

      void test()

{

                  Inner inner = new Inner();

                  inner.display(); }

      // this is an inner class

class Inner

{

      void display()

{

      System.out.println("display: outer_x = " + outer_x);

      }

   }

}

class InnerClassDemo

{

      public static void main(String args[])

 {

                   Outer outer = new Outer();

                   outer.test();

 }

 }

Output from this application is shown here:

 display: outer_x = 100

 

 

No comments:

Post a Comment