• No results found

Default Constructor :

In document Core Java Meterial (Page 147-173)

Overriding in the case of static methods

Case 1: Suppose in the derived class if there is no main method, then the parent class

5. Default Constructor :

Every class should have the constructor that may be written by programmer (or) generated by compiler.

If the programmer is not placing any constructor, then only compiler places (or) generates “Default Constructor”.

If the programmes already provided any constructor, then the compiler won’t general any default constructor. I.e. Either programmer provided constructor (or) compiler generated constructor is possible but not both simultaneously.

Proto type of Default Constructor :

- The access modifier of the default constructor is same as access modifier of the class (either public or default).

- Default constructor is always no argument constructor only.

- The Default constructor contains only one line i.e. a no argument call to the super class constructor. [Super ( );]

Eg :

Public Class Test { Public Test ( ) { Super( ); } }

Programmer’s Code Compiler General Code

1. Class Test Class Test

{ { Test( )

} {Super( );

} }

2. Public Class Test Public Class Test

{ {

} Public Test ( )

{ Super( ); }

}

3. Class Test Class Test

{ { Test ( ) Test ( ) { { } Super( ); } } }

4. Class Test Class Test

{ {

Test (int i) Test (int i)

{ {

Super( ); Super ( );

} }

} }

{ {

Void Test (int i) Void Test (int i)

{ } { } Test ( ) { Super ( ); } } Overloaded Constructors :

1. For any class we can write any number of constructors and are considered as overloaded constructors.

2. By using “Super” and “this”, we will invoke other constructors.

“Super” can be used for calling (invoking) parent class constructor and “this” can be used for invoking overloaded constructors of the same class. Eg :

Class Test {

Test ( ) { // Super( );

SOP (“No arg constructor”); }

Test (int i) {

This ( );

SOPln (“Int Constructor”); }

Test (double d) {

This (10);

SOPln (“Double Constructor”); }

P S V M(S[ ] args) {

} }

O/P : No arg constructor Int Constructor Double Constructor

this. i – invoking a member (variable / method) this ( ) – invoking a constructor

super. i – invoking parent class member super ( ) – invoking a parent class constructor

3. In every constructor, the first line should be a call to either a super class constructor (Super ( );) (or) a call to overloaded constructor (this ( );)

If u r not providing anything either super( ) (or) this( ) then the compiler always places super( ) by default.

(Automatic primitive casting is done in case of overloaded constructors) 4. Super( ) and this( ):

i. We should use Super( ) and this( ) in constructors only. i.e. we can invoke a constructor from another constructor only. We can’t invoke a constructor directly from a method.

ii. We should use only one but not both.

iii. We can use either super( ) (or) this( ) must be as the 1st statement

only.

iv. If U don’t keep Super ( ) (or) this( ), then compiler always places no argument Super( ) as the 1st Statement in a Constructor.

Eg : Class Test { Test ( ) { Super( ); this ( ); } Void M1( ) { this ( ); }

5. We can overload a constructor but inheritance and overriding is not possible. ⇒ Parents class variables & method r available to child class, but constructors won’t be available.

Case (i): Recursive method call is always a run problem. JVM rises Stack Over Flow Error. But, compiler point of view there is no problem at all. Eg : Class Test { Void M2( ) { M1( ); } Void M1( ) { M2 ( ); } P S V M(String[ ] args) {

Test t = new Test( ); t.M1( );

} } NO CTE

RTE : Java.lang. Stack Over Flow Error

6. But in case of constructors, recursive constructor invocation is a compile time error. Compiler is responsible for checking everything related to constructors. Eg : Class Test { Test( ) { this(10); } Test (int i) {

this( ); } P S V M(S[ ] a) { SOP(“Hello”); } }

CTE : Recursive constructor invocation.

Compiler checks about constructor because if pgmgr didn’t provide, compiler has to provide default constructor.

Case (ii) : Compiler’s Code

Class P Class P { { } P ( ) {Super( );} Class C extends P } { Class C extends P } { (C) {Super( );} }

NO CTE : Compiles Successfully.

Case (iii) : Compiler’s Code

Class P Class P { { P(int I) P (int i) { { } Super( ); Class C extends P } { } } Class C extends P { C ( ) {Super( ); } }

But parent class already contain constructor with int argument, - already 1 contest is present compiler won’t generate any default constr./ So, Super( ) ⇒ calling which is not present.

Conclu : If the parent class has same argument constructor, it is suggestible to

place always no argument constructor also, otherwise, while writing child class constructors, we should take care of calling super class constructor properly. Class P Class P { { P(int i) P (int i) { { } Super( ); } } Class C extends P } { Class C extends P C (int i) } } C(int i) } { } Super( ); } }

CTE : bcoz no-arg constructor is not there in P class.

Case (iii) : If the parent class – constructor throws some checked exception, the child class constructors also should throw the same checked exception or its parent (Higher type).

Eg: Class P 1 C ( ) throws Exption

{ {

P( ) throws exception{ } Super( ); NOCTE

} } Class C extends P { 2 C( ) C ( ) {Super( );} { } tru { Catch (Exception C) { }

CTE : Super must be stmt. CTE : Unreported exception java.lang. Exception, must be caught or

declared to be thrown.

Exception Handling : 1. Exception :

An “Exception” is an unexpected event which disturbs entire flow of the program.

Eg : Arithmetic Exception Null Pointer Exception File not Found Exception

2. If an exception occurred, the program terminates abnormally, which is not at all suggestible because it may effect the performance of the system.

To overcome this problem, we should handle the exception for graceful termination of your program.

3. “Exception Handling” means V r providing alternative possibility but it does not mean that v r repairing the exception.

Default Exception Handling in Java :

/* For every thread, a separate stack is there. Main is a thread. For every

method calls performed by that method is stored in that run-time stack. Eg: Class Test

{ P S V M(S[ ] a) { do stuff( ); } P S V do stuff( ) } do more stuff( ); } P S V do more stuff( ); { SOP (“Hi”); } } */

1. For every thread, there is corresponding run-time stack is associated. For every method call, one entry is going to store in the stack which is called “Activation record” (or) “Stack frame”, whenever the method completes, the corresponding record entry from the stack will be popped out automatically. If the last method also going to be completed, then the thread is ready to die (or) destroy. Before destroying thread, the corresponding stack object will be destroyed first.

{ P S V M(S[ ] args) { do stuff( ); } P S V do stuff( ) } do more stuff( ); } P S V do more stuff( ); {

SOP (“Hi, h r u”); }

}

Eg. Describing Default Exception Handling:

Class Test {

P S V M(S[ ] args) {do stuff ( );} P S V do stuff( ) {do more stuff ( );} P S V do more stuff( ) {SOP (10/0);} }

1. If any exception is coming, the corresponding method is responsible for the creation of Except Object.

/* Explanation :

⇒ Exception happened in do more stuff ( ) method, now the same method is responsible for creating an Exception Object which includes :

Exception Object : What is the Exception Where it is occurred What is the reason

Object to the JVM. JVM 1st removes do more stuff( ) checks who is the

cause for calling do more stuff, it finds stuff then it deletes that method & go to main & deletes that main also and calls default reception handle. The DEH provides the cause of exception.

*/

2. The Exception object contains the following into : i) Name of the Exception

ii) Description of the Exception

iii) Location where it occurred (stack trace)

3. After creation of Exception object, the method hand over the object to the JVM.

4. JVM will check for the handler in that method. If it is not finding any handler then JVM terminates that method abnormally and the corresponding entry from the stack will be removed.

5. It repeats the same process for the caller of the method. Even in the caller if it is not finding the exception handler then it will terminate that method followed by removing corresponding entry from the stack.

6. The whole process is repeated until main method. Even in the main method, if JVM is not finding the Handler it will terminate main method also abnormally and the corresponding thread will be terminated.

7. JVM hand over the responsibility of exception handling to the Default Exception Handler.

8. The Default Exception Handler just displays the error info on the console, nothing more.

RTE for pgm 2 :

Exception in thread main : Arithmetic Exception : / by zero at test. do more stuff (at test. java : 33)

at test. do stuff (at test. java : 18) at test. main (at test. java : 4)

Case :

Put SOP (10/0) Statement in i) do stuff method

ii) main method and see the O/P.

Exception Handling :

Throwable

Exception Error

(We can handle) (We can’t handle)

(recoverable) (irrecoverable)

Linkage Assertion Virtual Mk Error Error Error

Verify No Class Def Out of Memory Stack Over

Error Found Error Error flow error

Can be handled by pgmgr.

/* byte code verifier is part of JVM which checks whether generated. Class

file is by java C (Compiler) or not */ . Exception

Run time IO IO SQL Remote

Exception Exception Exception Exception Exception

Arithmetic Exception Null Pinter Exception

Index Out of Bound Exception

Array Index Out of Bound Exception String Index Out of Bound Exception Class Cast Exception

Illegal State Exception

Array Index Out Of Bounds Exception

Checked Versus Unchecked Exceptions :

- The Exceptions which r checked by compiler for the smooth execution of the pgm at Run time r called “Checked Exceptions”.

Eg : IO Exception.

- The Exceptions which r unable to check by the compiler r called “Unchecked Exceptions”. Run time Exceptions.

Eg : Arithmetic Exception

- Run time Exception and its child classes, error and its child classes r unchecked but the remaining r considered as checked exceptions.

Partially Vs Tully Checked Exceptions :

- A checked Exception is said to be fully checked if and only if all its child classes also checked. Eg : IO Exception.

- A checked Exception is said to be partially checked if some of its sub classes r checked its subclasses need not be checked. Eg. Exception.

1 We can implement Exception – Handling by using try – catch statements. The risky code we keep in inside ‘try’ block and the corresponding handlers, we can keep inside ‘catch’.

Eg: Class Test { P S V M(S[ ] args) { SOPln(“Stmt1” ); try { SOP (10/0); }

Catch (Arithmetic Exception) { SOPln(“Stmt2”); } } O/P : Stmt 1 5 Stmt 2 Eg: try { Stmt 1; Stmt 2; Stmt 3; } Catch (X e) { Stmt 4; } Stmt 5 ;

Case (i) : If there is no exception.

⇒ Stmt 1,23 followed by 5 will be executed. Indicates Normal Termination.

has matched.

⇒ Stmt 1,4 followed by 5 will be executed. Indicates Normal Termination.

Case (iii) : An exception raised at Stmt 2 and the corresponding catch block has

has matched.

⇒ Stmt 1 only will be executed. Indicates Normal Termination.

Methods for displaying error info :

1 Throwable class contain the following 3 methods for displaying error info. i) Print stack trace ( ) : We will get error info in the following format.

Name of the Exception : Description stack trace.

ii) to string ( ) method : This method displays error information in the following format.

Name of the Exception : Description.

iii) get Message ( ) Method : This method displays error info in the following format :

description arithmetic

Eg : Catch (Exception e) {

e. print Stack Trace ( ); SOP (e. to String( )); SOP (e. get Message ( )); }

try with multiple catch blocks :

1. It is a good programming practice to place a separate catch block for every exception, because the way of handling the exception is varied from one exception to another.

2. If V have multiple catch blocks, the order of catch blocks is very important. V should take child to parent, violation leads to CTE saying :

Exception has already been caught.

Eg: try try

{ {

SOP (10/0); SO(10/0);

} }

Catch (AE e) Catch (Exception e)

{ } { }

Catch (Exception e) Catch (AE e)

{ } { }

CTE :

NO CTE Exception : java. lang. AE Has already been caught.

Control – flow in nested try - catch :

Eg : try Possible Combination of x and y : { x : AE E AE E

Stmt 1; y : E AE AE E Stmt 2;

Stmt 3; In this pgm, we can’t compare the Try order of inner and outer catches. { But either complete inner, (or)

Stmt 4; complete outer we can compare. Stmt 5;

Stmt 6; }

Catch (x e) {

Stmt 7; } Stmt 8; } Catch (x e) { Stmt 9; } Stmt 10;

Case (i) : Exception raised at stmt 2 and corresponding catch block has found. Flow : Stmt 1, 9 followed by 10

Normal Termination.

Case (ii) : If there is no exception

Flow : Stmt 1, 2, 3 , 4, 5, 6, 8 followed by 10 Normal Termination.

Case (iii) : Exception raised at Stmt 2 and corresponding catch block has

not found.

Flow : Stmt 1 only Abnormal Termination.

Case (iv) : Exception raised at Stmt 5 and the corresponding inner catch has

matched.

Flow : 1,2,3,4,7,8 and 10 Normal Termination.

Case (v) : Exception raised at Stmt 5 but the inner catch has not matched but

Outer catch has matched. Flow : 1,2,3,4,9 and 10 Normal Termination.

Case (vi) : Exception raised at Stmt 5 but inner and outer catch blocks

r not matched. Flow : 1,2,3,4

Case (vii) : Exception raised at Stmt 8, the corresponding catch block has matched. Flow : 1,2,3,4,5,6,9 and 10 1,2,3,4,5,7,9 and 10 1,2,3,4,5,7,9 and 10 1,2,3,4,5,6,9 and 10 Normal Termination.

Case (viii) : If an Exception raised at Stmt 7 and the corresponding catch block

has matched.

Flow : 1,2,3,4,5,6,7,9 and 10 Normal Termination.

Case (ix) : Exception raised at Stmt 7 but the corresponding catch block has not

matched.

Flow : 1,2,3,4,5,6 Abnormal Termination.

Case (x) : Exception raised at Stmt 9 (or) Stmt 10

Flow : 1,2,3,4,5,6 Abnormal Termination.

Note : We can place try block within catch block.

Generic : Wherever java code is present, we can place it inside try – catch.

“Finally” : /* try { Open read close } Catch( ) {

}

∗/

1. Placing all these 3 in single try is not suggestible because there is no guarantee that all the 3 stmts. Must be executed whenever an Exception is occurred.

2. If U place that code in catch because no guarantee that catch executes always.

3. We can’t keep in both because of redundancy.

1. For the graceful terminal of the program, we have to deal locate all the resources like :

- Closing DB Connection, - Closing N/W Streams…

2. This clean-up code is not suggestible to place in try block because there is no guarantee for the execution of all d stmts/.. in try block.

3. It is not suggestible to place clean-up code in catch blocks also because if an exception not raised the corresponding catch block won’t execute. So we need a place for keeping clean-up code which should always execute whether an exception raised or not raised whether an exception is handled or not handled.

Such place is “finally” block.

Hence finally block will always execute even in the case of abnormal termination also. Eg : Class Test { P S V M (String[ ] args) { SOP (“Hai”);

Catch (AE e) { SOP(“Caught”); } Finally {

SOP (“finally block”); }

SOP(“Hello---“); }

}

O/P : 1. Hai finally block 2. Caught finally block

3. Finally block abnormal terminate 4. Finally block

5. RTE Exception

After execution of finally in case of abnormal termination no stmt. Would be executed.

Note : If a stmt/. Outside try-catch-finally is causing exception then, because try-catch is not concerned abt that stmt/. So finally block won’t be executed.

‘return’ stmt, anywhere indicates stopping the execution of that method.

Suppose if u place return stmt in try block, finally executes first then return stmt is executed.

The finally will always executed once u entered into the try block, even in the case of return statement also. But, if v r calling explicitly system.exit(O), Method, (⇒shutdown JVM Programme) the finally won’t execute. This is the only exceptional case where the finally block won’t execute.

Final : is a modifier applicable to variables, methods and classes.

Finally : To execute clean-up code irrespective of exception occurrence / handling

we keep that code in finally block.

Finalized : It is also for maintaining clean-up code only, (just before destroying

unreferred obj). .finalized( )

Finally & Finalized : is better be finally always executes where as we don’t know

when GC occurs. */

$ final, finally and finalized :

Final : It is the modifier which can be applied for variables, methods and classes.

- Final variable means – Constant.

- Final method – It can’t be overridden. - Final class – It can’t be inherited.

⇒ We can’t create child class.

Finally : This is the block associated with try-catd. For maintaining cleanup code. This block will always execute whether an exception is handled or not handled (or) an has raised or not.

Finalized ( ) : It is a method available in object class which contain clean-up

code, just before destroying any object, GC (Garbage Collector) calls finalize ( ) method for releasing the resources associated with that object.

When compared to finalize( ) method, finally block is always suggestible bcoz when the Garbage Collector. Runs finalize( ) we can’t predict (give any assurance).

Possible Combinations of try-catch-finally :

1. try

\ {

}

{ } finally { } VALID

B/W try and catch (or) b/w catch block (or) b/w catch and finally. V r not allowed to keep any stmt, violation leads to compile-time error.

Saying :

(i) try without catch or finally

(ii) catch without finally. (Null Pointer Exception) 2. try { } Catch ( ) { } VALID

No clean-up code, no finally block. 3. try { } finally { } VALID

The code which is not handled by try but compulsorily executed should be placed in try – finally, later pgm gets terminated & DEH cones into picture. 4. try

{ }

IN VALID

5. try { } finally { } Catch( ) { }

Order should be followed. Only 1 error occurs. Try finally cal ready there. Catch without finally – error.

Note : We can place try-catch in finally also.

Control flow in try-catch-finally :

1. try { Stmt 1; Stmt 2; Stmt 3; } Catch ( ) { Stmt 4; } finally { Stmt 5; } Stmt 6;

Case (i) : If there is no exception. Flow : 1,2,3,5 & 6 Normal Termination.

Case (ii) : Exception at Stmt 2 & corresponding catch matched.

Flow : 1,4,5 & 6 Normal Termination.

Flow : 1, 5

Abnormal Termination.

Case (iv) : Exception at Stmt 4.

Flow : Exception at 1 (or) 2 (or) 3……. 5 Abnormal Termination.

Case (v) : Exception at Stmt 5 (or) Stmt 6.

Abnormal Termination.

Control flow in nested try-catch-finally blocks :

1. try { Stmt 1; Stmt 2; Stmt 3; try { Stmt 4; Stmt 5; Stmt 6; } Catch ( ) { Stmt 7; } finally { Stmt 8; } Stmt 9; } Catch ( ) { Stmt 10; } finally ( ) { Stmt 11; } Stmt 12;

Case (1) : If there is no exception.

Flow : 1,2,3,4,5,6,8,9, 11 & 12 Normal Termination (N.T)

Case (2) : An Exception at Stmt 2 and Corresponding catch block has found

Flow : 1,10,11 & 12 Normal Termination.

Case (3) : Exception at Stmt 2 and Corresponding catch has not matched.

Flow : 1, 11

Abnormal Termination (A.T)

Case (4) : Exception at Stmt 5 and corresponding inner catch has matched.

Flow : 1,2,3,4,7,8,9, 11 and 12 Normal Termination.

Case (5) : Exception at Stmt 5, but inner catch has not matched,

out catch matched.

Flow : 1,2,3,4, 8,10, 11 and 12 Normal Termination.

Case (6) : Exception at Stmt 5, inner & catch did not match.

Flow : 1,2,3,4,8,11 followed by (A.T)

Case (7) : Exception at Stmt 7 and corresponding catch (outer) has matched.

Flow : 1,2,3,4,5,6,8,10, 11 and 12 Normal Termination.

Case (8) : Exception at Stmt 7, but catch (outer) has not matched.

Flow : 1,2,3,4,5,6,8,11 Abnormal Termination. Case (9) : Exception at Stmt 8, Stmt 9, Stmt 10, Stmt 11, Stmt 12. Abnormal Termination. “throws” clause : class test { P S V M(S[ ] args) { do stuff ( ); } P S V do stuff( ) { do more stuff ( ); } P S V do more stuff ( ) {

SOPln (“Hi”); thread.sleep (2000); }

}

CTE : Unreported exception, java.lang.IE. Must be caught or declared to be thrown.

Sleep method rises exception IE, because it is predictable that while it is sleeping any one can interrupt ⇒ checked exception.

1. “throws” clause is used for legating the responsibility of handling exception to the caller.

If there is any chance for rising checked exception, we should handle that exception explicitly otherwise we have to delegate that responsibility to the caller. Violation leads to CTE. Eg : class sample { P S V M(S[ ] args) { thread.sleep (1000); } }

Here, Sleep method throws a checked “Interrupted Exception”. V should handle this exception by using try-catch (or) V can deligate that responsibility to the caller, by using “throws”. But v didn’t perform anything, hence it is a CTE.

CTE : Unreported Exception : java.lang. Interrupted Exception; Must be caught or declared to be thrown.

Eg : class test { P S V M(S[ ] args) throws IE { do stuff ( ); } P S V do stuff( ) throws IE { do more stuff ( ); }

P S V do more stuff( ) throws IE {

} }

“throw” Keyword :

1. We can use ‘throw’ keyword for hand over exception object to the JVM. Some times, it is required to create our own customized exception objects and we have to handover to the JVM we can achieve this by using ‘throw’ keyword.

Eg : class test {

P S V M(S[ ] args) {

throw new Arithmetic Exception ( ); }

}

throw = Handover that object to JVM

Arithmetic Exception ( ); = Creation of Exception Object

2. After throw, v r not allowed to keep any statement directly, violation leads to CTE, saying: Unreachable Statement. Eg : class test { P S V M(S[ ] a) {

throw new Arithmetic Exception ( ); SOP (“Hai”);

} }

CTE : Unreachable Statement

3. In real-time it is not allowed to throw default exception objects, generally throw customized object.

4. V can throw any “throw able” instance (any exception or error) by using throw keyword.

Eg : class test {

Static Arithmetic Exception e; P S V M(S[ ] a)

{

throw e; // throwing null to JVM but not object }

}

CTE : Null Pointer Exception.

CTE (4) : (New Point)

If the try block doesn’t have any chance to throw some fully checked exception, then v r not allowed to place catch block for such fully checked exceptions. Violation leads to CTE, saying.

Exception is never thrown in body of corresponding try statement, i.e. v r not allowed to keep for catch blocks for fully checked exceptions unnecessary.

In document Core Java Meterial (Page 147-173)

Related documents