Search Java Programs

Thursday, January 7, 2010

Classes and Methods

The general class and main() method

public class {
type instace_variable1;
type instace_variable2;
type method_name1(parameters){ }
type method_name2(parameters){ }
public static void main(String[] args) {
System.out.println("Java");
}
}
Classes Introduction

A class is declared by the use of class keyword. The general form of a class is given above. The class with the main method initiates execution of a program. There can be classes created without main method. These classes will act as a user defined data types or the type definition.
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. In most of the cases, the instance variables are acted upon and accessed by methods defined for that class. Thus, it is the methods that determine how a class' data can be used.
Variables defined within a class are called instance variables because each instance of the class contains its own copy of these variables. All methods have the same general form as the main(). However, most methods will not be specified as static or public. Java classes do not need to have a main() method.
Classes can contain static member subroutines, as well as static member variables. For example, the System class contains a subroutine named exit. In a program, of course, this subroutine must be referred to as System.exit. Calling this subroutine will terminate the program. You could use it if you had some reason to terminate the program before the end of the main routine.
The subroutine call statement might look like "System.exit(0);" or "System.exit(1);". exit(0) means the program ends normally. Any other value means the program exits because of error detection.

A Simple class

Here is a class called as Box that defines three variables : length, width and height. Currently class box does not contains any methods. In this case we have created a new data type called Box.
class Box {
int length;
int width;
int height;
}
This class can be used in other classes for declaring member objects.

For example:

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

Box mybox = new Box();
// creating object and calling the constructor
mybox.width = 5; // assignment of values
mybox.height = 10;
mbox.length = 20;

System.out.println( "The height of the box is " +mybox.height);
System.out.println( "The width of the box is " +mybox.width);
System.out.println( "The length of the box is " +mybox.length);
}
// Printing values by calling System package methods

} //end of the class

Constructors

Constructor name is class name. A constructors must have the same name as the class its in. Default constructor.
If you don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value.
Default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created.

Differences between methods and constructors.
There is no return type given in a constructor signature. The value is this object itself so there is no need to indicate a return value. There is no return statement in the body of the constructor.
The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super() ). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.
These differences in syntax between a constructor and method are sometimes hard to see when looking at the source. It would have been better to have had a keyword to clearly mark constructors as some languages do.

this(...) Calls another constructor in same class. Often a constructor with few parameters will call a constructor with more parameters, giving default values for the missing parameters. Use this to call other constructors in the same class.

super(...) Use super to call a constructor in a parent class. Calling the constructor for the superclass must be the first statement in the body of a constructor. If you are satisfied with the default constructor in the superclass, there is no need to make a call to it because it will be supplied automatically.

Parameterised Constructors

Constructors and methods differ in three aspects of the signature: modifiers, return type, and name. Like methods, constructors can have any of the access modifiers: public, protected, private, or none. Unlike methods, constructors can take only access modifiers. Therefore, constructors cannot be abstract, final, native, static, or synchronized.

The return types are very different too. Methods can have any valid return type, or no return type, in which case the return type is given as void. Constructors have no return type, not even void.

Finally, in terms of the signature, methods and constructors have different names. Constructors have the same name as their class; by convention, methods use names other than the class name. If the Java program follows normal conventions, methods will start with a lowercase letter, constructors with an uppercase letter. Also, constructor names are usually nouns because class names are usually nouns; method names usually indicate actions

Garbage Collection

The name "garbage collection" implies that objects no longer needed by the program are "garbage" and can be thrown away. A more accurate and up-to-date metaphor might be "memory recycling." When an object is no longer referenced by the program, the heap space it occupies can be recycled so that the space is made available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed.
New objects are allocated, and unreferenced objects are freed such that free portions of heap memory are left in between portions occupied by live objects. Requests to allocate new objects may have to be filled by extending the size of the heap even though there is enough total unused space in the existing heap. This will happen if there is not enough contiguous free heap space available into which the new object will fit. On a virtual memory system, the extra paging (or swapping) required to service an ever growing heap can degrade the performance of the executing program. On an embedded system with low memory, fragmentation could cause the virtual machine to "run out of memory" unnecessarily.
A second advantage of garbage collection is that it helps ensure program integrity. Garbage collection is an important part of Java's security strategy. Java programmers are unable to accidentally (or purposely) crash the Java virtual machine by incorrectly freeing memory.

The finalise() method

Before an object is garbage collected, the runtime system calls its finalize() method. The intent is for finalize() to release system resources such as open files or open sockets before getting collected. Your class can provide for its finalization simply by defining and implementing a method in your class named finalize(). Your finalize() method must be declared as follows:

protected void finalize () throws throwable
This class opens a file when its constructed:

class OpenAFile {
FileInputStream aFile = null;
OpenAFile(String filename) {
try {
aFile = new FileInputStream(filename);
}
catch (java.io.FileNotFoundException e) {
System.err.println("Could not open file " + filename);
}
}
}


To be well-behaved, the OpenAFile class should close the file when its finalized. Here's the finalize() method for the OpenAFile class:

protected void finalize () throws throwable {
if (aFile != null) {
aFile.close();
aFile = null;
}
}


The finalize() method is declared in the java.lang.Object class. Thus when you write a finalize() method for your class you are overriding the one in your superclass. Overriding Methods talks more about how to override methods.

If your class's superclass has a finalize() method, then your class's finalize() method should probably call the superclass's finalize() method after it has performed any of its clean up duties. This cleans up any resources the object may have unknowingly obtained through methods inherited from the superclass.

protected void finalize() throws Throwable {
. . .
// clean up code for this class here
. . .
super.finalize();
}


Overloading Methods

Overloading is used in the standard Java classes. The System.out.println method accepts multiple parameter lists. This sample code snippet is valid:

System.out.println("Builder.com");

as is this one:

int test = 2; System.out.println(test);

Both code snippets compile and execute with no problems. The println method has been designed to accept varying parameters, so overloading is applicable beyond constructors.

Recursion
It is the central Simply put, recursion is when a function calls itself. That is, in the course of the function definition there is a call to that very same function. At first this may seem like a never ending loop, or like a dog chasing its tail. It can never catch it. So too it seems our method will never finish. This might be true is some cases, but in practise we can check to see if a certain condition is true and in that case exit (return from) our method

class Factorial {
int fact(int n) {
int result;
if ( n ==1) return 1;
result = fact (n-1) * n;
return result;
}
}

public class Recursion {
public static void main (String args[]) {
Factorial f =new Factorial();
System.out.println(“Factorial of 3 is “ + f.fact(3));
System.out.println(“Factorial of 3 is “ + f.fact(4));
System.out.println(“Factorial of 3 is “ + f.fact(5));
}
}

The output from this program is shown here:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
The final Keyword
A variable can be declared as final. Doing so prevents its contents from being modified. This means we have to initialize the variable when it is declared. Keyword final in java is similar to "const" in c / c++. The value of final variables will remain same through out the application.

For example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;

Arrays Revisited
Arrays are aslo implemented as objects. Hence there is a special array attribute to tell the size of the array, that is teh number of elements that an array can hold is found in its length instance variable. All arrays have this variabe, and it will always hold the size of the array. Here is a program that demonstrates this property.

public class Length {
int l;
public static void main(String args[]){
int n1[] = new int[10];
int n2[] = {3, 5, 7, 1, 8, 99, 44, -10);
int n3[] = { 4, 3, 2, 1);

System.out.println(“Length of n1 is “ + n1.length);
System.out.println(“Length of n2 is “ + n1.length);
System.out.println(“Length of n3 is “ + n1.length);
}

The output from this program is shown here:
Length of n1 is 10
Length of n2 is 8
Length of n3 is 4

No comments:

Post a Comment

Website Design by Mayuri Multimedia