Core Java Programming
(BCA 512)
By
Anuj Kumar Raghav
(TMU07531)
Unit 2
INHERITANCE
Inheritance is the capability of acquire property (variables) and behaviors (methods) of
another class is called inheritance.
1. The main purpose of the inheritance is code extensibility whenever we are extending
automatically the code is reused.
2. In inheritance one class giving the properties and behavior and another class is taking the
properties and behavior.
3. Inheritance is also known as is-a relationship means two classes are belongs to the same
hierarchy.
4. By using extends keyword we are achieving inheritance concept.
5. In the inheritance the person who is giving the properties is called parent the
person who is taking the properties is called child.
6. To reduce length of the code and redundancy of the code sun peoples
introducing inheritance concept.
Types of Inheritance
1. Single Inheritance
In this inheritance one derived class inherits from only one base class. It is the
simplest form of inheritance.
2. Multiple Inheritance
In this type of inheritance a single derived class inherits from two or more than
two base classes.
3. Multilevel Inheritance
In this type of inheritance the derived class inherits from a class, which is turn
inherits from some other class. The super class for one is sub class for another
class.
4. Hierarchical Inheritance
In this type of inheritance multiple derived classes are inherits from a single base class.
5. Hybrid Inheritance
Hybrid inheritance is combination of multiple and multilevel inheritance. Two or
more type of inheritance are used to design called Hybrid inheritance.
1. Single
Inheritance
class Animal{
1. void eat(){System.out.println("eating...");}
2. }
3. class Dog extends Animal{
4. void bark(){System.out.println("barking...");}
5. }
6. class TestInheritance{
7. public static void main(String args[]){
8. Dog d=new Dog();
9. d.bark();
10. d.eat();
11. }}
2. Multilevel
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
3. Hierarchal
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there
will be compile time error.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Test it Now
Compile Time Error
Superclass
A superclass is the class from which many subclasses can be created. The subclasses inherit the
characteristics of a superclass. The superclass is also known as the parent class or base class.
Subclass
In Java, a subclass is a class that inherits from another class.
Object class
Object class is present in java.lang package. Every class in Java is directly or indirectly derived
from the Object class.
Using Object Class Methods
toString() method
hashCode() method
equals(Object obj) method
finalize() method
getClass() method
clone() method
wait(), notify() notifyAll() methods
Final Keyword in Java
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
1. variable
2. method
3. class
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
Output:Compile Time Error
2) Java final method
If you make any method as final, you cannot override it.
1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Test it Now
Output:Compile Time Error
3) Java final class
If you make any class as final, you cannot extend it.
1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }
Test it Now
Output:Compile Time Error
Super Key-word
Super:- Super keyword is used to represent
1) Call the Super class variable.
2) Call the super class constructor.
3) Call the super class methods.
Super keyword is not required
class Parent
{
int a=10;
int b=20;
}
class Child extends Parent
{
int x=100;
int y=200;
void add(int i,int j)
{
System.out.println(i+j);
System.out.println(x+y);
System.out.println(a+b);
}
public static void main(String[] args)
{
Child c=new Child();
c.add(1000,2000);
}
}
Super keyword is required
class Test1
{
int a=10;
int b=20;
};
class Test extends Test1
{
int a=100;
int b=200;
void add(int a,int b)
{
System.out.println(a+b);
System.out.println(this.a+this.b);
System.out.println(super.a+super.b);
}
public static void main(String[] args)
{
Test t=new Test();
t.add(1000,2000);
}}
Inner and Nested classes
Non-static nested classes are called inner classes. Nested classes that are declared static are
called static nested classes. A nested class is a member of its enclosing class. Non-static nested
classes (inner classes) have access to other members of the enclosing class, even if they are
declared private.
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}
// Outputs 15 (5 + 10)
Package
A package is a collection of related Java entities (such as classes, interfaces, exceptions, errors and
enums).
Packages are used for:
Resolving naming conflict of classes by prefixing the class name with a package name. For
example, com.zzz.Circle and com.yyy.Circle are two distinct classes. Although they share the same
class name Circle, but they belong to two different packages: com.zzz and com.yyy.
CLASSPATH is an environment variable (i.e., global variables of the operating system available to all the
processes) needed for the Java compiler and runtime to locate the Java packages/classes used in a Java
program.
Syntax
import packageName.ClassName;
Types of Packages in Java
java. lang.
java.io.
java. util.
java. applet.
java. awt.
java.net.
Modifiers
Modifiers are the keyword which define the accessibility or scope of a variable , class
method in the program.
The public members can be accessed everywhere.
The private members can be accessed only inside the same class.
The protected members are accessible to every child class (same package or other packages).
The default members are accessible within the same package but not outside the package.
Interface in Java
An interface in Java is a blueprint of a class. The interface in Java is a mechanism to achieve
abstraction. There can be only abstract methods in the Java interface, not method body. It is used
to achieve abstraction and multiple inheritance in Java.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.
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. }
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. }
Exception Handling in Java
An exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime. The Exception Handling in Java is one of the powerful mechanism to handle
the runtime errors so that the normal flow of the application can be maintained.
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error.
Types of Java Exceptions
Checked Exception
Unchecked Exception
Error
Java Exception Keywords
Keyword Description
The "try" keyword is used to specify a block where we should place an exception code. It
try means we can't use try block alone. The try block must be followed by either catch or
finally.
The "catch" block is used to handle the exception. It must be preceded by try block which
catch
means we can't use catch block alone. It can be followed by finally block later.
The "finally" block is used to execute the necessary code of the program. It is executed
finally
whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
The "throws" keyword is used to declare exceptions. It specifies that there may occur an
throws exception in the method. It doesn't throw an exception. It is always used with method
signature
Example 1
1. public class TryCatchExample2 {
2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. //handling the exception
9. catch(ArithmeticException e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }
Test it Now
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 2
1. public class TryCatchExample9 {
2.
3. public static void main(String[] args) {
4. try
5. {
6. int arr[]= {1,3,5,7};
7. System.out.println(arr[10]); //may throw exception
8. }
9. // handling the array exception
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. System.out.println(e);
13. }
14. System.out.println("rest of the code");
15. }
16.
17. }
Test it Now
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Java Catch Multiple Exceptions
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
At a time only one exception occurs and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception
Example 1
1. public class MultipleCatchBlock1 {
2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Test it Now
Output:
Arithmetic Exception occurs
rest of the code
Example 2
24. public class MultipleCatchBlock1 {
25.
26. public static void main(String[] args) {
27.
28. try{
29. int a[]=new int[5];
30. System.out.println(a[10]); }
31. catch(ArithmeticException e)
32. {
33. System.out.println("Arithmetic Exception occurs");
34. }
35. catch(ArrayIndexOutOfBoundsException e)
36. {
37. System.out.println("ArrayIndexOutOfBounds Exception occurs");
38. }
39. catch(Exception e)
40. {
41. System.out.println("Parent Exception occurs");
42. }
43. System.out.println("rest of the code");
44. }
45. }
Test it Now
Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code
In this example, try block contains two exceptions. But at a time only one exception occurs
and its corresponding catch block is executed.
Example 3
46. public class MultipleCatchBlock1 {
47.
48. public static void main(String[] args) {
49.
50. try{
51. int a[]=new int[5];
52. a[5]=30/0;
53. System.out.println(a[10]);
54. }
55. catch(ArithmeticException e)
56. {
57. System.out.println("Arithmetic Exception occurs");
58. }
59. catch(ArrayIndexOutOfBoundsException e)
60. {
61. System.out.println("ArrayIndexOutOfBounds Exception occurs");
62. }
63. catch(Exception e)
64. {
65. System.out.println("Parent Exception occurs");
66. }
67. System.out.println("rest of the code");
68. }
69. }
Test it Now
Output:
Arithmetic Exception occurs
rest of the code
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).
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 completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
10. System.out.println("rest of the code...");
11. }
12. }
Test it Now
Output:
Compile-time error
Java finally block
Java finally block is always executed whether an exception is handled or not.
Case 1: When an exception does not occur
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:
Case 2: When an exception occurr but not handled by the catch block
Let's see the the fillowing example. Here, the code throws an exception however the catch
block cannot handle it. Despite this, the finally block is executed after the try block and then the
program terminates abnormally.
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
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.
1. public class TestFinallyBlock2{
2. public static void main(String args[]){
3.
4. try {
5.
6. System.out.println("Inside try block");
//below code throws divide by zero exception
int data=25/0;
10. System.out.println(data);
11. }
12.
13. //handles the Arithmetic Exception / Divide by zero exception
14. catch(ArithmeticException e){
15. System.out.println("Exception handled");
16. System.out.println(e);
17. }
18.
19. //executes regardless of exception occured or not
20. finally {
21. System.out.println("finally block is always executed");
22. }
23.
24. System.out.println("rest of the code...");
25. }
26. }
Output:
Java throw Exception
In Java, exceptions allows us to write good quality codes where the errors are checked at the
compile time instead of runtime and we can create custom exceptions making the code recovery
and debugging easier.
Example
In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
1. public class TestThrow1 {
2. //function to check if person is eligible to vote or not
3. public static void validate(int age) {
4. if(age<18) {
5. //throw Arithmetic exception if not eligible to vote
6. throw new ArithmeticException("Person is not eligible to vote");
7. }
8. else {
9. System.out.println("Person is eligible to vote!!");
10. }
11. }
12. //main method
13. public static void main(String args[]){
14. //calling the function
15. validate(13);
16. System.out.println("rest of the code...");
17. }
18. }
Output:
Java throws Exception
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception.
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. }
Test it Now
Output:
exception handled
normal flow...
Java I/O
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all
the classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes.
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Depending on the type of operations, streams can be divided into two primary classes:
Input Stream: These streams are used to read data that must be taken as an input from a
source array or file or any peripheral device.
Output Stream: These streams are used to write data as outputs into an array or file or
any output peripheral device.
Depending on the types of file, Streams can be divided into two primary classes which can
be further divided into other classes.
ByteStream: This is used to process data byte by byte (8 bits).
Stream class Description
BufferedInputStream It is used for Buffered Input Stream.
DataInputStream It contains method for reading java standard datatypes.
Stream class Description
FileInputStream This is used to reads from a file
InputStream This is an abstract class that describes stream input.
PrintStream This contains the most used print() and println() method
BufferedOutputStream This is used for Buffered Output Stream.
DataOutputStream This contains method for writing java standard data types.
FileOutputStream This is used to write to a file.
OutputStream This is an abstract class that describe stream output.
CharacterStream: In Java, characters are stored using Unicode conventions (Refer this for
details). Character stream automatically allows us to read/write data character by character.
Stream class Description
BufferedReader It is used to handle buffered input stream.
FileReader This is an input stream that reads from file.
InputStreamReader This input stream is used to translate byte to character.
OutputStreamReader This output stream is used to translate character to byte.
Reader This is an abstract class that define character stream input.
PrintWriter This contains the most used print() and println() method
Writer This is an abstract class that define character stream output.
BufferedWriter This is used to handle buffered output stream.
FileWriter This is used to output stream that writes to file.
Java FileOutputStream Example 1: write byte
1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. fout.write(65);
7. fout.close();
8. System.out.println("success...");
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
Serialization and Deserialization in Java
Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly
used in Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization where byte-stream is converted into
an object.
For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for
deserialization we call the readObject() method of ObjectInputStream class.
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java
classes so that the objects of these classes may get a certain capability. The Cloneable and Remote
are also marker interfaces.
The Serializable interface must be implemented by the class whose object needs to be persisted.
The String class and all the wrapper classes implement the java.io.Serializable interface by default.
Let's see the example for Serialization given below:
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
class Persist{
public static void main(String args[]){
try{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}catch(Exception e){System.out.println(e);}
}
}
Example of Java Deserialization
Deserialization is the process of reconstructing the object from the serialized state. It is the reverse
operation of serialization. Let's see an example where we are reading the data from a deserialized
object.
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
class Depersist{
public static void main(String args[]){
try{
//Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
//printing the data of the serialized object
System.out.println(s.id+" "+s.name);
//closing the stream
in.close();
}catch(Exception e){System.out.println(e);}
}
}