Module 3 & 4 Mix (Shivani Ma - Am)
Module 3 & 4 Mix (Shivani Ma - Am)
Inheritance:
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviours of parent object. The idea behind inheritance in java is that you can create new
classes that are built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship. The
class which inherits the properties of other is known as subclass (derived class, child class) and
the class whose properties are inherited is known as superclass (base class, parent class).
extends is the keyword used to inherit the properties of a class.
1. class Employee
2. {
3. float salary=40000;
4. }
5.
6. class Programmer extends Employee
7. {
8. int bonus=10000;
9. public static void main(String args[])
{
Programmer p=new Programmer();
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
barking...
eating...
Multilevel Inheritance:
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from
a derived class, thereby making this derived class the base class for the new class.
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();
}
}
weeping...
barking...
eating..
Hierarchical Inheritance :
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//Compile Time.Error
}}
meowing...
eating...
Polymorphism:
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java:
• compile time polymorphism and
• runtime polymorphism.
Compile Time polymorphism can be achieved using overloading methods
Run Time Polymorphism can be achieved using overriding methods
Runtime Polymorphism
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.
Child class has the same method as of base class. In such cases child class overrides the parent
class method without even touching the source code of the base class.
class Bank{
float getRateOfInterest(){
return 0;
}
}
class SBI extends Bank{
float getRateOfInterest(){
return 8.4f;
}
}
class ICICI extends Bank{
float getRateOfInterest(){
return 7.3f;
}
}
class AXIS extends Bank{
float getRateOfInterest(){
return 9.7f;
}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7
NOTE : Static methods cannot be overridden because, a static method is bounded with class
where as instance method is bounded with object.
Super Keyword:
The super keyword in java is a reference variable which is used to refer immediate parent class
object. Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
class Vehicle
{
int maxSpeed = 120;
}
void display()
{
System.out.println("Derived class Speed: " + maxSpeed);
System.out.println("Base Speed: " + super.maxSpeed);
}
}
The super keyword can also be used to invoke or call parent class method. It should be used
in case of method overriding. In other word super keyword use when base class method name
and derived class method name have same name.
class Student
{
void message()
{
System.out.println("Good Morning Sir");
}
}
void display()
{
message(); //will invoke or call current class message() method
super.message(); //will invoke or call parent class message() method
}
The super keyword can also be used to invoke or call the parent class constructor.
Constructor are calling from bottom to top and executing from top to bottom.
To establish the connection between base class constructor and derived class constructors
JVM provides two implicit methods they are: If super is not used explicitly compiler will
automatically add super as the first statement.
• Super()
• Super(...)
Super():
Super() It is used for calling super class default constructor from the context of derived
class constructors.
class Employee
{
Employee()
{
System.out.println("Employee class Constructor");
}
}
class HR extends Employee
{
HR()
{
super(); //will invoke or call parent class constructor
System.out.println("HR class Constructor");
}
}
class Supercons
{
public static void main(String[] args)
{
HR obj=new HR();
}
}
Employee class Constructor
HR class Constructor
Super(...)
Super(...) It is used for calling super class parameterize constructor from the context of
derived class constructor.
class Person
{
int id;
String name;
class TestSuper5
{
Important rules
Rule for default constructor
Whenever the derived class constructor want to call default constructor of base class, in the
context of derived class constructors we write super(). It is optional to write because every
base class constructor contains single form of default constructor
Rule for Parameterized constructor
Whenever the derived class constructor wants to call parameterized constructor of base class
in the context of derived class constructor we must write super(...). which is mandatory to
write because a base class may contain multiple forms of parameterized constructors.
Abstract Classes
An abstract class is a class that is declared abstract—It can have abstract and non-abstract
methods (method with body).Abstract classes cannot be instantiated, but they can be
subclassed.
That is we cannot create an object for abstract classes
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
• To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
• If you inherit an abstract class, you have to provide implementations to all the abstract
methods in it.
Abstract method
Method that is declared without any body within an abstract class is called abstract method.
The method body will be defined by its subclass. Abstract method can never be final and static.
Any class that extends an abstract class must implement all the abstract methods declared by
the super class.
Syntax :
class TestAbstraction
{
public static void main(String args[])
{
Rectangle r = new Rectangle();
r.draw();
Shape s=new Circle();
s.draw();
}
}
drawing rectangle
drawing circle
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
void changeGear(){
System.out.println("gear changed");}
}
Packages:
Packages in Java is a mechanism to encapsulate a group of classes, interfaces and sub
packages.To create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the specified
package. The package statement defines a name space in which classes are stored. If you omit
the package statement, the class names are put into the default package, which has no name.
This is the general form of the package statement:
package pkg;
Java uses file system directories to store packages. For example, the .class files for any classes
you declare to be part of MyPackage must be stored in a directory called MyPackage.
package pkg1[.pkg2[.pkg3]];
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not sub packages. The import keyword is used to make the classes and interface of another
package accessible to the current package.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
1) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
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. 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. }
}
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
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. }
Access Specifiers
• private: accessible only in the class
• default : so-called “package” access — accessible only in the same package
• protected: accessible (inherited) by subclasses, and accessible by code in same package
• public: accessible anywhere the class is accessible, and inherited by subclasses
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
• A user has entered an invalid data.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Difference between error and exception
Errors indicate serious problems and abnormal conditions that most applications should not
try to handle. Error defines problems that are not expected to be caught under normal
circumstances by our program. For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions.
Few examples –
• DivideByZero exception
• NullPointerException
• ArithmeticException
• ArrayIndexOutOfBoundsException
Exception hierarchy
1) Checked: are the exceptions that are checked at compile time. If some code within a method
throws a checked exception, then the method must either handle the exception or it must specify
the exception using throws keyword.
Example, consider the following Java program that opens file at location “C:\test\a.txt” and
prints the first three lines of it. The program doesn’t compile, because the function main() uses
FileReader() and FileReader() throws a checked exception FileNotFoundException. It also
uses readLine() and close() methods, and these methods also throw checked exception
IOException
2) Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions
are unchecked, so it is not forced by the compiler to either handle or specify the exception. It
is up to the programmers to be civilized, and specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions,
everything else under throwable is checked.
try-catch –
try is the start of the block and catch is at the end of try block to handle the exceptions.
We can have multiple catch blocks with a try and try-catch block can be nested also. catch
block requires a parameter that should be of type Exception.
A catch block must be associated with a try block. The corresponding catch block
executes if an exception of a particular type occurs within the try block.
For example if an arithmetic exception occurs in try block then the statements enclosed
in catch block for arithmetic exception executes.
import java.io.*;
class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}
All the statements in the catch block will be executed and then the program continues.
If the exception type of exception, matches with the first catch block it gets caught, if not the
exception is passed down to the next catch block.
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Warning: ArithmeticException
Out of try-catch block...
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.Java finally block is always executed whether exception is handled or not.
Finally block is optional and can be used only with try-catch block. Since exception halts
the process of execution, we might have some resources open that will not get closed, so we
can use finally block. finally block gets executed always, whether exception occurred or not
1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e)
8. {
9. System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Exception Handling is mainly used to handle the checked exceptions. If there occurs
any unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
throws – When we are throwing any exception in a method and not handling it, then we need
to use throws keyword in method signature to let caller program know the exceptions that
might be thrown by the method. The caller method might handle these exceptions or propagate
it to its caller method using throws keyword. We can provide multiple exceptions in the throws
clause and it can be used with main() method also.
throw –
We know that if any exception occurs, an exception object is getting created and then
Java runtime starts processing to handle them. Sometime we might want to generate exception
explicitly in our code, for example in a user authentication program we should throw exception
to client if the password is null. throw keyword is used to throw exception to the runtime to
handle it.
Throw instance();
where,
instance is of object type of an exception.
Example:
throw new ArithmeticException("/ by zero");
import java.io.*;
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException ("demo Exception ");
}
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught in main\n" + e);
}
}
}
Output:Inside check function
caught in main
throw throws
Using throw keyword you can declare only Using throws keyword you can declare
one Exception at a time multiple exception at a time.
Example: Example:
import java.io.*;
}
public double getAmount()
{
return amount;
}
}
public class Main
{
private double balance;
private int number;
public Main(int balance)
{
this.balance = balance;
}
}
}
Output:
Hello World
Sorry, but you are short $1000.0
InsufficientFundsException
at Main.withdraw(Main.java:42)
Interfaces:
An interface in java is a blueprint of a class. It has static constants and abstract methods.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.
Java Interface also represents IS-A relationship.It cannot be instantiated just like abstract
class.
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
Implementing Interfaces
A class uses the implements keyword to implement an interface.
Syntax:
1. interface Bank
2. {
3. float rateOfInterest();
4. }
5.
6. class SBI implements Bank
7. {
8. public float rateOfInterest()
9. {
10. return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{
return 9.7f;
}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}
1 abstract class can extend only one class or one interface can extend any number of
abstract class at a time interfaces at a time
2 abstract class can extend from a class or from an interface can extend only from an
abstract class interface
3 abstract class can have both abstract and interface can have only abstract methods
concrete methods
4 A class can extend only one abstract class A class can implement any number of
interfaces
}
public interface Drawable {
public abstract void draw();
double radius;
Circle(double aRadius){
radius= aRadius;
}
double area(){
return Math.PI*radius*radius;
}
}
Class test
{
Public static void main(String args[])
{
Shape obj= new Rectangle();
Shape obj1= new Circle();
obj.draw();
obj1.draw();
}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}
Output: ROI: 9.15
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class Test implements Printable,Showable{
8. public void print(){
9. System.out.println("Hello");}
Output:Hello
Welcome
interface Inf1{
public void method1();
}
interface Inf2 extends Inf1 {
public void method2();
}
public class Demo implements Inf2{
/* Even though this class is only implementing the
* interface Inf2, it has to implement all the methods
* of Inf1 as well because the interface Inf2 extends Inf1
*/
public void method1(){
System.out.println("method1");
}
public void method2(){
System.out.println("method2");
}
public static void main(String args[]){
Inf2 obj = new Demo();
obj.method2();
}
}
Final methods:
While method overriding is one of Java’s 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.
class Bike
{
final void run()
{
System.out.println("running");
}
}
Final Class:
Sometimes you will want to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final implicitly declares all of its methods as final,
too. As you might expect, it is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its subclasses to provide complete
implementations.
Here is an example of a final class:
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 Honda();
8. honda.run();
9. }
}
Output:Compile Time Error
Final variable
If you make any variable as final, you cannot change the value of final variable
(It will be constant).
1. class Bike
2. {
3. final int speedlimit=90; //final variable
4. void run()
5. {
6. speedlimit=400;
7. }
8. public static void main(String args[]){
9. Bike9 obj=new Bike9();
obj.run(); //Compile Time Error
}
}
Compile Time Error