Sei sulla pagina 1di 114

Web Programming

Unit III Features of Java


- Designed to provide solutions to some of the problems in modern programming. - They wanted the language to be not only reliable, portable and distributed but also
Simple Compact Interactive

Sun microsystem officially describes Java with the following attributes:

Compiled & Interpreted


A computer language is either compiled or interpreted. Java combines both these approaches together to make java as a two stage systems. Compiler translates source code into byte code instructions. Byte codes are not machine instructions. Interpreter generates machine code that can be directly executed by the machine that is running the java program.

Simple

no pointers, preprocessor header files, goto stmt etc., automatic garbage collection

Eliminates operator overloading, multiple inheritance.


Everything in java is an object. all functions are associated with objects almost all data types are objects (files, strings, etc.) All program code and data reside within objects and classes.

Object oriented

Platform independent & Portable Java programs can be easily moved from one computer system to another, anywhere and anytime. If there is any changes in OS, processors will not force any changes in Java programs. Because of this, Java has become very popular for programming on Internet.

Multithreading Handling multiple tasks simultaneously. i.e need not wait for the application to finish one task before beginning another. High Performance: Due to the use of intermediate bytecode.

Robust & Secure Java has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. It provides many safeguards to ensure reliable code. It has strict compile & run time checking for data types.

Java also incorporates the concept of exception handling which captures errors and eliminates any risk of crashing the system. Distributed Java is designed as a distributed language for creating applications on networks. Ability to share both data and programs. Java applications can open and access remote objects on internet as easily as they can do in a local system.

Dynamic

It is a dynamic language. Capable of linking new class libraries, methods and objects dynamically.

How Java Differs from C


Major Difference Java is a Object_oriented language. Java doesnot include C unique stmts, keywords sizeof, typeof Java doesnot contain datatypes struct & union Java doesnot define the type modifier keywords auto, extern, register, signed and unsigned. Java doesnot support Explicit pointer type. Java doesnot have a preprocessor. So we cannot use #define, #include and #ifdef Java adds break & continue stmts., instanceof operator, many features for oops.

How Java differs from C++


Java is a true Object Oriented Language while c++ is c with object-oriented extension. Java does not support Operator overloading Java does not have template classes Java does not support multiple inheritance. This is implemented in java called as Interface Java does not use pointers Java does not support global variables. Java has replaced the destructor function with a finalize() function No header files in java

Java Platform

Java includes large number of development tools and hundreds of classes & methods. Development tools are part of the system known as JDK and the classes and methods are part of Java Std. Library(JSL) also known as API(Application Programming Interface).

JDK
Collection of tools that are used for developing and running java programs. They include, AppletViewer (for viewing java applets) Javac(for compiler) Java(for interpreter) Javah(for c header files) Javap(Java disassembler) Javadoc(for creating HTML documents) Jdb(Java debugger)

AppletViewer Enables us to run java applets Javac translates java sourcecode to bytecode files that the interpreter can understand Java runs applets & applications Javah It produces header files Javap which enables us to convert bytecode files into a pgm. description Javadoc - for creating HTML documents from java source code file. Jdb which helps us to find errors in our program.

Overview of Java Language


Java is general purpose, object-oriented language. Two types of java programs:


1.

2.

Stand alone applications Web applets

Stand alone applications it is a program written in java to do certain language works on a stand-alone computer. For executing this, 2 steps are available:

Compiling Source code into bytecode using javac compiler Executing the byte code program using java interpreter.

Java Applets It is a small java program developed for Internet applications


For executing this, 2 steps are available:

Compiling Source code into bytecode using javac compiler Executing the byte code program using appletviewer.

Simple Java Program


Create the source file:

open a text editor, key in the code which defines a class (HelloWorldApp) and then save it in a file (HelloWorldApp.java) Here file name and class name are case sensitive and must be matched exactly (except the .java part)

Example Code: HelloWorldApp.java public class HelloWorldApp { public static void main(String[] args) { // Display "Hello World!" System.out.println("Hello World!"); } }

Java is

CASE SENSITIVE!

In the first line HelloWorldApp, declares a class which is an object oriented construct. Class -> Keyword HelloWorldApp Specifies the name of the class to be defined. Every class definition in Java must begin with { and ends with }.

The third line, public static void main(String args[]) defines a method named main. (Its similar to main() in c/c++).
Every java pgm. must include the main() method. This is the starting point for the interpreter to begin the execution of the pgm. A java app. can have any no. of classes but only one must have a main() method to initiate the execution. It contains a no. of keywords, public, static and void.

Public it is an access specifier that declares the main method as interpreted and it is accessible to all other classes. Static It allows main() to be called without having to instantiate a particular instance of a class. Void It states that the main() method does not return any value. All parameters to a method are declared inside a pair of parenthesis. Only one parameter is available called
String args[ ] declares a parameter named args which contains an array of objects of the class type String.

The output line,


System.out.println(Hello World); This is similar to printf stmt in C or cout stmt in C++.

Compile the program: compile HelloWorldApp.java by using the following command:


javac HelloWorldApp.java it generates a file named HelloWorldApp.class which contains the byte code version of the program. internal or external command,

javac is not recognized as an operable program or hatch file.

javac: Command not found if you see one of these errors, you have two choices: 1) specify the full path in which the javac program locates every time. For example: C:\ Program Files\Java\jdk1.5.0\bin \javac HelloWorldApp.java 2) set the PATH environment variable, set path=C:\Program Files\Java\jdk1.5.0\bin

Run the program:


run the code through:


java HelloWorldApp

Note that the command is java, not javac, and you refer to HelloWorldApp, not HelloWorldApp.java or HelloWorldApp.class
thread "main" java.lang.NoClassDefFoundError:

Exception in
HelloWorldApp

if you see this error, you may need to set the environment variable CLASSPATH For setting the classpath, z:\>set classpath=%classpath%;.;

Class Example { public static void main(String args[ ]) { int num; // declaration num = 100; // assign num as 100 System.out.println(This is num: +num); num = num * 2; System.out.println(This is num * 2 : +num); } } Output: This is num: 100 This is num * 2 : 200 Here the + sign causes the value of num to be appended to the string that proceeds it and then the resulting string is the output.

Data Types
Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float, double, and boolean. These can be put in four groups: Integers This group includes byte, short, int, and long, which are for whole valued signed numbers. Floating-point numbers This group includes float and double, which represent numbers with fractional precision. Characters This group includes char, which represents symbols in a character set, like letters and numbers. Boolean This group includes boolean, which is a special type for representing true/false values.

Primitive Data Types


Data type byte short int long float double char -128 .. 127 (8 bits) -32,768 .. 32,767 (16 bits) -2,147,483,648 .. 2,147,483,647 (32 bits) -9,223,372,036,854,775,808 .. ... (64 bits) +/-10-38 to +/-10+38 and 0, about 6 digits precision +/-10-308 to +/-10+308 and 0, about 15 digits precision Unicode characters (generally 16 bits per char) Range of values

boolean

True or false

Integers

Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values. Java does not support unsigned, positive-only integers Byte: The smallest integer type is byte. This is a signed 8-bit type that has a range from 128 to 127. Example: byte b, c (b, c are variable name)

short It is a signed 16-bit type. It has a range from 32,768 to 32,767. This type is mostly applicable to 16-bit computers Example: short s, t; int The most commonly used integer type is int. It is a signed 32bit type that has a range from 2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly employed to control loops and to index arrays.

long It is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. The range of a long is quite large.

Floating point types


Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. It consists of float, double. Float: The type float specifies a single-precision value that uses 32 bits of storage Example: float hightemp, lowtemp;

Double Double precision, as denoted by the double keyword, uses 64 bits to store a value. Math functions, such as sin( ), cos( ), and sqrt( ), return double values. // Compute the area of a circle. class Area { public static void main(String args[ ]) { double pi, r, a; r = 10.8; // radius of circle pi = 3.1416; // pi, approximately a = pi * r * r; // compute area System.out.println("Area of circle is " + a); }}

Characters: In Java, the data type used to store characters is char. char in Java is not the same as char in C or C++. In C/C++, char is an integer type that is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode(ASCII) to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages.

// Demonstrate char data type. class CharDemo { public static void main(String args[]) { char ch1, ch2; ch1 = 88; // code for X ch2 = 'Y'; System.out.print("ch1 and ch2: "); System.out.println(ch1 + " " + ch2); } } This program displays the following output: ch1 and ch2: X Y (ch1 is assigned the value 88 which is the ASCII value that corresponds to the letter X).

// char variables behave like integers. class CharDemo2 { public static void main(String args[]) { char ch1; ch1 = 'X'; System.out.println("ch1 contains " + ch1); ch1++; // increment ch1 System.out.println("ch1 is now " + ch1); } } The output generated by this program is shown here: ch1 contains X ch1 is now Y In the program, ch1 is first given the value X. Next, ch1 is incremented. This results in ch1 containing Y, the next character in the ASCII (and Unicode) sequence.

Booleans

Java has a simple type, called boolean, for logical values. It can have only one of two possible values,

true

or false

Variables

The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer.

Declaring a Variable In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ; type data type identifier is the name of the variable. We can initialize the variable by specifying an equal sign and a value.

Example: int a, b, c; // declares three ints, a, b, and c. int d = 3, e, f = 5; // declares three more ints, initializing // d and f. byte z = 22; // initializes z. double pi = 3.14159; // declares an approximation of pi. char x = 'x'; // the variable x has the value 'x'.

Dynamic Initialization
Java allows variables to be initialized dynamically, using any valid expression at the time the variable is declared.
Program to compute the length of the hypotenuse of a right triangle given the lengths of its two opposing sides:

// Demonstrate dynamic initialization. class DynInit { public static void main(String args[]) { double a = 3.0, b = 4.0; double c = Math.sqrt(a * a + b * b); // c is dynamically initialized System.out.println("Hypotenuse is " + c); }}

Here,

three local variables a, b, and c are declared.

The
c

first two a and b are initialized by constants.

is initialized dynamically to the length of the hypotenuse. built-in method sqrt( ) is a member of Math class and it is used to compute the square root of its argument.

Javas

Type Conversion and Casting


Java performs type conversion automatically. When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met: The two types are compatible. The destination type is larger than the source type. When these two conditions are met, a widening conversion takes place. Some conversion will not perform automatically, this kind of conversion is narrowing conversion.

Syntax for Type Casting

(target type) value target-type specifies the desired type to convert the specified value.

Demonstrate casts.
class Conversion { public static void main(String args[]) { byte b; int i = 257; double d = 323.142; System.out.println("\nConversion of int to byte."); b = (byte) i; System.out.println("i and b " + i + " " + b); System.out.println("\nConversion of double to int."); i = (int) d; System.out.println("d and i " + d + " " + i); System.out.println("\nConversion of double to byte."); b = (byte) d; System.out.println("d and b " + d + " " + b); } }

This program generates the following output: Conversion of int to byte. i and b 257 1 Conversion of double to int. d and i 323.142 323 Conversion of double to byte. d and b 323.142 67

Arrays

An array is a group of related data items that share a common name. One-Dimensional Arrays To create an array, first we must create an array variable of the desired type. General form: type var-name[ ]; type declares the base type of the array. The base type determines what type of data the array will hold.

Creating an Array

Arrays must be declared and created in the computer memory before they are used. It involves three steps.

Declaring the array Creating memory locations Putting values into the memory locations.

Declaration of Arrays: It may declared in two ways. 1. type arrayname[ ]; Ex: int num[ ]; 2. type[ ] arrayname; Ex: int[ ] num; Creation of arrays: Java allows us to create arrays using new operator. arrayname = new type[size]; Ex: number = new int[5];

Initialization of arrays: The final step is to put values into the array created. 1. arrayname[subscript]=value; Ex: num[0]=11, num[1]=12,..num[4]=15 2. type arrayname[ ]={list of values} int val[4]={12,13,15,17,18}

Demonstrate a one-dimensional array.

class Array { public static void main(String args[]) { int month_days[]; month_days = new int[12]; month_days[0] = 31; month_days[1] = 28; month_days[2] = 31; month_days[3] = 30; month_days[4] = 31; month_days[5] = 30; month_days[6] = 31; month_days[7] = 31;

month_days[8] = 30; month_days[9] = 31; month_days[10] = 30; month_days[11] = 31; System.out.println("April has " + month_days[3] + " days."); } } Output: April has 30 days

An improved version of the previous program.

class AutoArray { public static void main(String args[]) { int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 }; System.out.println("April has " + month_days[3] + " days."); } }

Multidimensional Arrays

In Java, multidimensional arrays are actually arrays of arrays. int twoD[ ][ ] = new int[4][5]; This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an array of arrays of int.

// Demonstrate a two-dimensional array.

class TwoDArray { public static void main(String args[]) { int twoD[][]= new int[4][5]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<5; j++) { twoD[i][j] = k; k++; }

for(i=0; i<4; i++) { for(j=0; j<5; j++) System.out.print(twoD[i][j] + " "); System.out.println(); }}}

Output:

01234 56789 10 11 12 13 14 15 16 17 18 19

Manually allocate differing size second dimensions.

class TwoDAgain { public static void main(String args[]) { int twoD[][] = new int[4][]; twoD[0] = new int[1]; twoD[1] = new int[2]; twoD[2] = new int[3]; twoD[3] = new int[4]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<i+1; j++) {

twoD[i][j] = k; k++; }
for(i=0; i<4; i++) { for(j=0; j<i+1; j++) System.out.print(twoD[i][j] + " "); System.out.println(); }}}

OUTPUT:

0 12 345 6789

Assignment 1 Operators

Control Statements
If - The if statement is Javas conditional branch statement. if (condition) statement1; else statement2; Nested ifs A nested if is an if statement that is the target of another if or else. if(i == 10) { if(j < 20) a = b; if(k > 100) c = d; // this if is else a = c; // associated with this else } else a = d; // this else refers to if(i == 10)

if-else-if Ladder A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder. It looks like this: if(condition) statement; else if(condition) statement; else if(condition) statement; ... else statement;

switch

The switch statement is Javas multiway branch statement. switch (expression) { case value1: // statement sequence break; case value2: // statement sequence break; ... case valueN: // statement sequence break; default: // default statement sequence } The expression must be of type byte, short, int, or char

Iteration Statements

Javas iteration statements are for, while, and do-while. These statements create what we commonly call loops. loop repeatedly executes the same set of instructions until a termination condition is met.

while

The while loop is Javas most fundamental looping statement. It repeats a statement or block while its controlling expression is true. General form: while(condition) { // body of loop } The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately following the loop.

do-while

The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. General form :
do { // body of loop } while (condition);

Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates.

for
General form of the for statement: for(initialization; condition; iteration) { // body } If only one statement is being repeated, there is no need for the curly braces. The for loop operates as follows. When the loop first starts, the initialization portion of the loop is executed. It is important to understand that the initialization expression is only executed once. Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop control variable against a target value.

If this expression is true, then the body of the loop is executed. If it is false, the loop terminates. Next, the iteration portion of the loop is executed. This is usually an expression that increments or decrements the loop control variable. This process repeats until the controlling expression is false.

Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside another. // Loops may be nested. class Nested { public static void main(String args[]) { int i, j; for(i=0; i<10; i++) { for(j=i; j<10; j++) System.out.print("."); System.out.println(); } } }

The output produced by this program is shown here:

.......... ......... ........ ....... ...... ..... .... ... .. .

Jump Statements
Java supports three jump statements: break, continue, and return. These statements transfer control to another part of the program Break: In Java, the break statement has three uses. It terminates a statement sequence in a switch statement. It can be used to exit a loop. It can be used as a form of go to.

Using break to Exit a Loop


// Using break to exit a loop. class BreakLoop { public static void main(String args[]) { for(int i=0; i<100; i++) { if(i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); } System.out.println("Loop complete."); } } This program generates the following output: i: 0 i: 1 i: 2 i: 3 i: 4 i: 5 i: 6 i: 7 i: 8 i: 9 Loop complete.

Using break as a Form of Goto


By using this form of break, you can break out of one or more blocks of code. These blocks need not be part of a loop or a switch. They can be any block. The general form of the labeled break statement: break label; label is the name of a label that identifies a block of code.

// Using break as a civilized form of goto. class Break { public static void main(String args[]) { boolean t = true; first: { second: { third: { System.out.println("Before the break."); if(t) break second; // break out of second block System.out.println("This won't execute"); } System.out.println("This won't execute"); } System.out.println("This is after second block."); } } }

Running this program generates the following output:

Before the break. This is after second block.

Using continue

The continue statement performs such an action. In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression. For all three loops, any intermediate code is bypassed.

return

The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method.

// Demonstrate return. class Return { public static void main(String args[]) { boolean t = true; System.out.println("Before the return."); if(t) return; // return to caller System.out.println("This won't execute."); } }

Output Before the return.

As you can see, the final println( ) statement is not executed. As soon as return is executed, control passes back to the caller.

Class

Class Fundamentals

Java is a true object-oriented language and the structure of all java programs are classes. Everything in java can be encapsulated in a class that defines the state and behavior of the basic pgm. Components called objects. Classes create objects and objects use methods to communicate between them. Class is a template for an object and an Object is an instance of a class.

The General Form of a Class


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 } }

A Simple Class
A class called Box that defines three instance variables: width, height, and depth. Currently, Box does not contain any methods class Box { double width; double height; double depth; }

Add methods that are necessary for manipulating the data contained in the class. Methods are declared within the body of the class immediately after the declaration of instance variables. Class declaration creates only a template, it does not create an object. To create an object, Box mybox = new Box()

mybox instance of Box class

To access the variable of class Box, use dot(.) operator. It links the name of the object with the name of the instance variable. To assign the width variable of mybox as 100,
mybox.width = 100;

/* 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 { 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); }}

// This program declares two Box objects. class Box { double width; double height; double depth; } class BoxDemo2 { 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

Methods
General form of a method: type name(parameter-list) { // body of method } Type specifies the type of data returned by the method. This can be any valid type, including class types that you create. If the method does not return a value, its return type must be void. Parameter-list always enclosed in parenthesis. It contains variable names & types of all the values. Body Operation to be performed on the data.

Adding a method to a class


// This program includes a method inside the box class. class Box { double width; double height; double depth; // display volume of a box void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); } } class BoxDemo3 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); // 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; // display volume of first box mybox1.volume(); // display volume of second box mybox2.volume(); } }

Constructors

To initialize an object, java supports special type of object called a constructor that enables an object to initialize itself when it is created. Constructors have the same name as the class name itself. Do not specify a return type, not even void.

class Box { double width; double height; double 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 BoxDemo6 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox = new Box(); double vol; // get volume of box vol = mybox.volume(); System.out.println("Volume is " + vol); } } Output: Constructing Box Volume is 1000.0

Parameterized Constructors
/* Here, Box uses a parameterized constructor to initialize the dimensions of a box. */ class Box { double width; double height; double 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 BoxDemo7 { 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); } } output Volume is 3000.0 Volume is 162.0

Garbage Collection

Objects are dynamically allocated by using the new operator, we dont know how such objects are destroyed and their memory released for later reallocation. In some languages, such as C++, dynamically allocated objects must be manually released by use of a delete operator. In Java, it handles deallocation automatically, this technique is known as garbage collection.

Overloading Methods

In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. This method is known as overloaded, and the process is referred to as method overloading.

OverloadDemo.java

Overloading Constructor

In addition to overloading normal methods, we can also overload constructor methods.

OverloadCons.java

Argument Passing

In general, there are two ways that a computer language can pass an argument to a subroutine. Call by value - This method copies the value of an argument into the formal parameter of the subroutine.

Therefore, changes made to the parameter of the subroutine have no effect on the argument.

Call by reference - reference to an argument (not the value of the argument) is passed to the parameter. Changes made to the parameter will affect the argument used to call the subroutine. As you will see, Java uses both approaches, depending upon what is passed.

// Simple types are passed by value. class Test { void meth(int i, int j) { i *= 2; j /= 2; }} class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.println("a and b before call: " + a + " " + b); ob.meth(a, b); System.out.println("a and b after call: " + a + " " + b); } }

The output from this program is shown here: a and b before call: 15 20 a and b after call: 15 20

operations that occur inside meth( ) have no effect on the values of a and b used in the call; their values here did not change to 30 and 10.

// Objects are passed by reference. class Test { int a, b; Test(int i, int j) { a = i; b = j; } // pass an object void meth(Test o) { o.a *= 2; o.b /= 2; }} class CallByRef { public static void main(String args[]) { Test ob = new Test(15, 20); System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.meth(ob); System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b); } }

This program generates the following output: ob.a and ob.b before call: 15 20 ob.a and ob.b after call: 30 10 The action inside meth() have affected the object used as an argument.

Recursion

Java supports recursion. Recursion is the process of defining something in terms of itself. Recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive.

// A simple example of recursion. class Factorial { // this is a recursive function int fact(int n) { int result; if(n==1) return 1; result = fact(n-1) * n; return result; } } 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 4 is " + f.fact(4)); System.out.println("Factorial of 5 is " + f.fact(5)); } }

Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120

Using Command-Line Arguments

Sometimes you will want to pass information into a program when you run it. This is can be done through command-line arguments to main( ). A command-line argument is the information that directly follows the programs name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easythey are stored as strings in the String array passed to main( ).

// Display all command-line arguments. class CommandLine { public static void main(String args[]) { for(int i=0; i<args.length; i++) System.out.println("args[" + i + "]: " + args[i]); } } Try executing this program, as shown here: java CommandLine this is a test 100 -1

args[0]: this args[1]: is args[2]: a args[3]: test args[4]: 100 args[5]: -1

FINAL Variables & Methods


All methods and variables can be overridden by default in subclasses. If we wish to prevent the subclasses from overriding the members of the superclass, declare them as final using the keyword final final int size = 100; final void show()

// functionality defined in this method will never be altered in any way. // Value of the final variable can never be changed.

{ . }

Inheritance Basics

To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. The following program creates a superclass called A and a subclass called B.

SimpleInheritance.java DemoBoxWeight.java

Member Access and Inheritance

Although a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared as private.
// Create a superclass. class A { int i; // public by default private int j; // private to A void setij(int x, int y) { i = x; j = y; } } // A's j is not accessible here. class B extends A { int total; void sum() { total = i + j; // ERROR, j is not accessible here }}

class Access { public static void main(String args[]) { B subOb = new B(); subOb.setij(10, 12); subOb.sum(); System.out.println("Total is " + subOb.total); }} This program will not compile because the reference to j inside the sum( ) method of B causes an access violation. Since j is declared as private, it is only accessible by other members of its own class. Subclasses have no access to it.

Super Keyword
Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super. super has two general forms. (i) The first calls the superclass constructor. (ii) The second is used to access a member of the superclass that has been hidden by a member of a subclass.

DemoBoxWeightSuper.java

Using super to Call Superclass Constructors

A subclass can call a constructor method defined by its superclass by use of the following form of super: super(parameter-list); Here, parameter-list specifies any parameters needed by the constructor in the superclass. super( ) must always be the first statement executed inside a subclass constructor.

A Second Use for super

The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. This usage has the following general form: super.member Here, member can be either a method or an instance variable.

// Using super to overcome name hiding. class A { int i; } // Create a subclass by extending A. class B extends A { int i; // this i hides the i in A B(int a, int b) { super.i = a; // i in A i = b; // i in B } void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); } }

class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } } This program displays the following: i in superclass: 1 i in subclass: 2 Although the instance variable i in B hides the i in A, super allows access to the I defined in the superclass. As you will see, super can also be used to call methods that are hidden by a subclass.

Creating a Multilevel Hierarchy


Simple class hierarchies consist of only a superclass and a subclass. We can build hierarchies that contain as many layers of inheritance as we like. It is perfectly acceptable to use a subclass as a superclass of another. Example, given three classes called A, B, and C, C can be a subclass of B, which is a subclass of A. When this type of situation occurs, each subclass inherits all of the traits found in all of its superclasses. In this case, C inherits all aspects of B and A. Eg: - DemoShipment.java

When Constructors Are Called


// Demonstrate when constructors are called. // Create a super class. class A { A() { System.out.println("Inside A's constructor."); } } // Create a subclass by extending class A. class B extends A { B() { System.out.println("Inside B's constructor."); } } // Create another subclass by extending B. As you can see, the constructors are called in order of derivation. class C extends B { C( ) { System.out.println("Inside C's constructor."); } } class CallingCons { public static void main(String args[]) { C c = new C(); } } The output from this program is shown here: Inside As constructor Inside Bs constructor Inside Cs constructor

Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. Override.java

When show( ) is invoked on an object of type B, the version of show( ) defined within B is used. That is, the version of show( ) inside B overrides the version declared in A.

If you wish to access the superclass version of an overridden function, you can do so by using super. For example, in this version of B, the superclass version of show( ) is invoked within the subclass version. This allows all instance variables to be displayed.

class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { super.show(); // this calls A's show() System.out.println("k: " + k); }}

If you substitute this version of A into the previous program, you will see the following output: i and j: 1 2 k: 3 Here, super.show() calls the superclass version of show( ).

Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded. Override1.java

Using final with inheritance - Using final to Prevent Overriding


While method overriding is one of Javas most powerful features, there will be times when you will want to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden. The following fragment illustrates final:

class A { final void meth() { System.out.println("This is a final method."); } } class B extends A { void meth() { // ERROR! Can't override. System.out.println("Illegal!"); } }

final class A { // ... } // The following class is illegal. class B extends A { // ERROR! Can't subclass A // ... }

Potrebbero piacerti anche