Module 2
Module 2
Abstraction in Java
Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
Another way, it shows only essential things to the user and hides
the internal details, for example, sending SMS where you type the
text and send the message. You don't know the internal processing
about the message delivery.
Abstraction lets you focus on what the object does instead of how it
does it.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to
change the body of the method.
Example of abstract class
running safely
File: TestAbstraction1.java
drawing circle
File: TestAbstraction2.java
1. class Bike12{
2. abstract void run();
3. }
1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am c");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}
https://www.youtube.com/watch?
v=p_4Dyfplqkw&list=PLLOxZwkBK52BaOQCJrVvkc97uzeMsx9TT&index=27
Output:I am a
I am b
I am c
I am d
Interface in Java
An interface in Java is a blueprint of a class. It has static constants
and abstract methods.
In other words, you can say that interfaces can have abstract
methods and variables. It cannot have a method body.
https://www.youtube.com/watch?v=3PJw1UAcGDo
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
In other words, Interface fields are public, static and final by default,
and the methods are public and abstract.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Output:
Hello
File: TestInterface1.java
Output:
drawing circle
File: TestInterface2.java
1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}
Output:
ROI: 9.15
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }
Output:Hello
Welcome
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestInterface3 implements Printable, Showable{
9. public void print(){System.out.println("Hello");}
10. public static void main(String args[]){
11. TestInterface3 obj = new TestInterface3();
12. obj.print();
13. }
14. }
Output:
Hello
Interface inheritance
A class implements an interface, but one interface extends another
interface.
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. TestInterface4 obj = new TestInterface4();
13. obj.print();
14. obj.show();
15. }
16. }
Output:
Hello
Welcome
File: TestInterfaceDefault.java
1. interface Drawable{
2. void draw();
3. default void msg(){System.out.println("default method");}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8. class TestInterfaceDefault{
9. public static void main(String args[]){
10. Drawable d=new Rectangle();
11. d.draw();
12. d.msg();
13. }}
Output:
drawing rectangle
default method
File: TestInterfaceStatic.java
1. interface Drawable{
2. void draw();
3. static int cube(int x){return x*x*x;}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8.
9. class TestInterfaceStatic{
10. public static void main(String args[]){
11. Drawable d=new Rectangle();
12. d.draw();
13. System.out.println(Drawable.cube(3));
14. }}
Output:
drawing rectangle
27
1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }
https://www.youtube.com/watch?
v=Mj8uanC2Wn0&list=PLLOxZwkBK52BaOQCJrVvkc97uzeMsx9TT&index=28
1) Abstract class can have abstract and Interface can have only abstract meth
non-abstract methods.
it can have default and static metho
3) Abstract class can have final, non- Interface has only static and final va
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the impleme
implementation of interface.
class.
6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java
interfaces.
8) A Java abstract class can have class Members of a Java interface are public
members like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
But there are many differences between abstract class and interface
that are given below.
Output:
I am a
I am b
I am c
I am d
Java Package
A java package is a group of similar types of classes, interfaces
and sub-packages.
There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-
defined packages.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
If you are not using any IDE, you need to follow the syntax given
below:
For example
1. javac -d . Simple.java
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination. The . represents the current folder.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this
package will be accessible but not subpackages.
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this
package will be accessible.
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello
Subpackage in java
Package inside the package is called the subpackage. It should be
created to categorize the package further.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
To Compile:
To Run:
To run this program from e:\source directory, you need to set classpath of the d
where the class file resides.
To run this program from e:\source directory, you can use -classpath
switch of java that tells where to look for class file. For example:
Output:Welcome to package
o Temporary
o Permanent
Rule: There can be only one public class in a java source file and
it must be saved by the public class name.
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}
https://www.youtube.com/watch?
v=OJZrkoR7i88&list=PLLOxZwkBK52BaOQCJrVvkc97uzeMsx9TT&index=30
Package class
The package class provides methods to get information about the
specification and implementation of a package. It provides methods
such as getName(), getImplementationTitle(),
getImplementationVendor(), getImplementationVersion() etc.
1. class PackageInfo{
2. public static void main(String args[]){
3.
4. Package p=Package.getPackage("java.lang");
5.
6. System.out.println("package name: "+p.getName());
7.
8. System.out.println("Specification Title: "+p.getSpecificationTitle());
9. System.out.println("Specification Vendor: "+p.getSpecificationVendo
r());
10. System.out.println("Specification Version: "+p.getSpecificationVersi
on());
11.
12. System.out.println("Implementaion Title: "+p.getImplementationTitl
e());
13. System.out.println("Implementation Vendor: "+p.getImplementation
Vendor());
14. System.out.println("Implementation Version: "+p.getImplementatio
nVersion());
15. System.out.println("Is sealed: "+p.isSealed());
16.
17.
18. }
19. }
Output:package name: java.lang
Specification Title: Java Plateform API Specification
Specification Vendor: Sun Microsystems, Inc.
Specification Version: 1.6
Implemenation Title: Java Runtime Environment
Implemenation Vendor: Sun Microsystems, Inc.
Implemenation Version: 1.6.0_30
IS sealed: false
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
If you make any class constructor private, you cannot create the
instance of that class from outside the class. For example:
1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
2) Default
If you don't use any modifier, it is treated as default by default. The
default modifier is accessible only within package. It cannot be
accessed from outside the package. It provides more accessibility
than private. But, it is more restrictive than protected, and public.
1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }
In the above example, the scope of class A and its method msg() is
default so it cannot be accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and
outside the package but through inheritance only.
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the
widest scope among all other modifiers.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello
1. class A{
2. protected void msg(){System.out.println("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){System.out.println("Hello java");}//C.T.Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. obj.msg();
10. }
11. }
https://www.youtube.com/watch?v=b54vqDFjAzk
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Do You Know?
o What is the difference between checked and unchecked exceptions?
o What happens behind the code int data=50/0;?
o Why use multiple catch block?
o Is there any possibility when the finally block is not executed?
o What is exception propagation?
o What is the difference between the throw and throws keyword?
o What are the 4 rules for using exception handling with method overriding?
1. Checked Exception
2. Unchecked Exception
3. Error
2) Unchecked Exception
3) Error
Keyword Description
catch The "catch" block is used to handle the exception. It must be preceded b
means we can't use catch block alone. It can be followed by finally bloc
finally The "finally" block is used to execute the necessary code of the program
throws The "throws" keyword is used to declare exceptions. It specifies that the
JavaExceptionExample.java
Output:
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
The catch block must be used after the try block only. You can use
multiple catch block with a single try block.
Internal Working of Java try-catch block
https://www.youtube.com/watch?
v=9kI0_F41i5Y&list=PLLOxZwkBK52BaOQCJrVvkc97uzeMsx9TT&index=29
Example 1
TryCatchExample1.java
1. public class TryCatchExample1 {
2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.
7. System.out.println("rest of the code");
8.
9. }
10.
11. }
Output:
Example 2
TryCatchExample2.java
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 3
In this example, we also kept the code in a try block that will not
throw an exception.
TryCatchExample3.java
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the
rest of the block code will not execute.
Example 4
Here, we handle the exception using the parent class exception.
TryCatchExample4.java
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5
Let's see an example to print a custom message on exception.
TryCatchExample5.java
Output:
Example 6
Let's see an example to resolve the exception in a catch block.
TryCatchExample6.java
1. public class TryCatchExample6 {
2.
3. public static void main(String[] args) {
4. int i=50;
5. int j=0;
6. int data;
7. try
8. {
9. data=i/j; //may throw exception
10. }
11. // handling the exception
12. catch(Exception e)
13. {
14. // resolving the exception in catch block
15. System.out.println(i/(j+2));
16. }
17. }
18. }
Output:
25
Example 7
In this example, along with try block, we also enclose exception
code in a catch block.
TryCatchExample7.java
Output:
Here, we can see that the catch block didn't contain the exception
code. So, enclose exception code within a try block and use catch
block only to handle the exceptions.
Example 8
In this example, we handle the generated exception (Arithmetic
Exception) with a different type of exception class
(ArrayIndexOutOfBoundsException).
TryCatchExample8.java
Output:
Example 9
Let's see an example to handle another unchecked exception.
TryCatchExample9.java
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Example 10
Let's see an example to handle checked exception.
Points to remember
o At a time only one exception occurs and at a time only one
catch block is executed.
o All catch blocks must be ordered from most specific to most
general, i.e. catch for ArithmeticException must come before
catch for Exception.
MultipleCatchBlock1.java
Output:
Example 2
MultipleCatchBlock2.java
Output:
MultipleCatchBlock3.java
Output:
Example 4
In this example, we generate NullPointerException, but didn't
provide the corresponding exception type. In such case, the catch
block containing the parent exception class Exception will invoked.
MultipleCatchBlock4.java
Output:
Example 5
Let's see an example, to handle the exception without maintaining
the order of exceptions (i.e. from most specific to most general).
MultipleCatchBlock5.java
1. class MultipleCatchBlock5{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed
");}
8. catch(ArithmeticException e){System.out.println("task1 is comple
ted");}
9. catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
10. System.out.println("rest of the code...");
11. }
12. }
Output:
Compile-time error
https://www.youtube.com/watch?v=hhK4zGplHTA
Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....
NestedTryBlock.java
Output:
When any try block does not have a catch block for a particular
exception, then the catch block of the outer (parent) try block are
checked for that exception, and if it matches, the catch block of
outer try block is executed.
Example 2
Let's consider the following example. Here the try block within
nested try block (inner try block 2) do not handle the exception. The
control is then transferred to its parent try block (inner try block 1).
If it does not handle the exception, then the control is transferred to
the main try block (outer try block) where the appropriate catch
block handles the exception. It is termed as nesting.
NestedTryBlock.java
Output:
TestFinallyBlock.java
1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. System.out.println(e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. System.out.println("finally block is always executed");
15. }
16.
17. System.out.println("rest of phe code...");
18. }
19. }
Output:
TestFinallyBlock1.java
1. public class TestFinallyBlock1{
2. public static void main(String args[]){
3.
4. try {
5.
6. System.out.println("Inside the try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. System.out.println(data);
11. }
12. //cannot handle Arithmetic type exception
13. //can only accept Null Pointer type exception
14. catch(NullPointerException e){
15. System.out.println(e);
16. }
17.
18. //executes regardless of exception occured or not
19. finally {
20. System.out.println("finally block is always executed");
21. }
22.
23. System.out.println("rest of the code...");
24. }
25. }
Output:
Case 3: When an exception occurs and is handled by
the catch block
Example:
Let's see the following example where the Java code throws an
exception and the catch block handles the exception. Later the
finally block is executed after the try-catch block. Further, the rest
of the code is also executed normally.
TestFinallyBlock2.java
Output:
Rule: For each try block there can be zero or more catch blocks,
but only one finally block.
Note: The finally block will not be executed if the program exits
(either by calling System.exit() or by causing a fatal error that
causes the process to abort).
TestThrow1.java
Output:
TestThrow2.java
1. import java.io.*;
2.
3. public class TestThrow2 {
4.
5. //function to check if person is eligible to vote or not
6. public static void method() throws FileNotFoundException {
7.
8. FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\
abc.txt");
9. BufferedReader fileInput = new BufferedReader(file);
10.
11.
12. throw new FileNotFoundException();
13.
14. }
15. //main method
16. public static void main(String args[]){
17. try
18. {
19. method();
20. }
21. catch (FileNotFoundException e)
22. {
23. e.printStackTrace();
24. }
25. System.out.println("rest of the code...");
26. }
27. }
Output:
Example 3: Throwing User-defined Exception
exception is everything else under the Throwable class.
TestThrow3.java
1. class TestExceptionPropagation1{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation1 obj=new TestExceptionPropagation1()
;
15. obj.p();
16. System.out.println("normal flow...");
17. }
18. }
Output:
exception handled
normal flow...
1. class TestExceptionPropagation2{
2. void m(){
3. throw new java.io.IOException("device error");//checked excepti
on
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handeled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation2 obj=new TestExceptionPropagation2()
;
15. obj.p();
16. System.out.println("normal flow");
17. }
18. }
Output:
Testthrows1.java
1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Output:
exception handled
normal flow...
Testthrows2.java
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. m.method();
12. }catch(Exception e){System.out.println("exception handled");}
13.
14. System.out.println("normal flow...");
15. }
16. }
Output:
exception handled
normal flow...
Testthrows3.java
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//
declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Output:
B) If exception occurs
Testthrows4.java
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOException{//
declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Output:
Difference between throw and throws
Click me for details
Output:
Java throw and throws Example
TestThrowAndThrows.java
Output:
Difference between final, finally and
finalize
The final, finally, and finalize are keywords in Java that are used in
exception handling. Each of these keywords has a different
functionality. The basic difference between final, finally and finalize
is that the final is an access modifier, finally is the block in
Exception Handling and finalize is the method of object class.
Along with this, there are many differences between final, finally
and finalize. A list of differences between final, finally and finalize
are given below:
It's execution is
not dependant on
the exception.
FinalExampleTest.java
Output:
FinallyExample.java
Output:
TestExceptionChild.java
1. import java.io.*;
2. class Parent{
3.
4. // defining the method
5. void msg() {
6. System.out.println("parent method");
7. }
8. }
9.
10. public class TestExceptionChild extends Parent{
11.
12. // overriding the method in child class
13. // gives compile time error
14. void msg() throws IOException {
15. System.out.println("TestExceptionChild");
16. }
17.
18. public static void main(String args[]) {
19. Parent p = new TestExceptionChild();
20. p.msg();
21. }
22. }
Output:
TestExceptionChild1.java
1. import java.io.*;
2. class Parent{
3. void msg() {
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild1 extends Parent{
9. void msg()throws ArithmeticException {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]) {
14. Parent p = new TestExceptionChild1();
15. p.msg();
16. }
17. }
Output:
1. import java.io.*;
2. class Parent{
3. void msg()throws ArithmeticException {
4. System.out.println("parent method");
5. }
6. }
7.
8. public class TestExceptionChild2 extends Parent{
9. void msg()throws Exception {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]) {
14. Parent p = new TestExceptionChild2();
15.
16. try {
17. p.msg();
18. }
19. catch (Exception e){}
20.
21. }
22. }
Output:
Output:
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception {
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild4 extends Parent{
9. void msg()throws ArithmeticException {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild4();
15.
16. try {
17. p.msg();
18. }
19. catch(Exception e) {}
20. }
21. }
Output:
1. import java.io.*;
2. class Parent {
3. void msg()throws Exception{
4. System.out.println("parent method");
5. }
6. }
7.
8. class TestExceptionChild5 extends Parent{
9. void msg() {
10. System.out.println("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild5();
15.
16. try {
17. p.msg();
18. }
19. catch(Exception e) {}
20.
21. }
22. }
Output:
Example 1:
Let's see a simple example of Java custom exception. In the
following code, constructor of InvalidAgeException takes a string as
an argument. This string is passed to constructor of parent class
Exception using the super() method. Also the constructor of
Exception class can be called without using a parameter and calling
super() method is not mandatory.
TestCustomException1.java
Output:
Example 2:
TestCustomException2.java
Output:
If all the class objects are a part of the outer object then it is easier
to nest that class inside the outer class. That way all the outer class
can access all the objects of the inner class.
Do You Know
Type Description
Member Inner A cl
Class
ass created within class and outside method.