Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 95

055CS75

PROGRAMMING IN JAVA
INHERITANCE
• Inheritance in Java is a mechanism in which one object acquires all
the properties and behaviors of a parent object.
• It is an important part of OOPs (Object Oriented programming
system).
• 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 the parent class. Moreover, you can add new methods and
fields in your current class also.
• Inheritance represents the IS-A relationship which is
also known as a parent-child relationship.
• SYNTAX
.
class Subclass-name extends Superclass-name  
{  
   //methods and fields  
}  
EXAMPLE

class Employee{  
float salary=40000;  
}  
class Programmer extends Employee{  
 int bonus=10000;  
 public static void main(String args[]){  
  Programmer p=new Programmer();  
  System.out.println("Programmer salary is:"+p.salary);  
   System.out.println("Bonus of Programmer is:"+p.bonus);  
}  
}  
Super Keyword in Java

• 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.
Usage of Java super Keyword

• super can be used to refer immediate parent class instance variable.


• super can be used to invoke immediate parent class method.
• super() can be used to invoke immediate parent class constructor.
Super is used to refer immediate parent class instance variable.

• We can use super keyword to access the data member or field of


parent class. It is used if parent class and child class have same fields.
class Animal{  
String color="white";  
}  
class Dog extends Animal{  
String color="black";  
void printColor()
{  
System.out.println(color);//prints color of Dog class  
System.out.println(super.color);//prints color of Animal class  
}  
}  
class TestSuper1{  
public static void main(String args[]){  
Dog d=new Dog();  
d.printColor();  
}}  
super can be used to invoke parent class method

• The super keyword can also be used to invoke parent class method.
• It should be used if subclass contains the same method as parent class.
• In other words, it is used if method is overridden.
class Animal{  
void eat()
{
System.out.println("eating...");
}  
}  
class Dog extends Animal{  
void eat(){
System.out.println("eating bread...");}  
void bark(){System.out.println("barking...");}  
void work(){  
super.eat();  
bark();  
}  
}  
class TestSuper2{  
public static void main(String args[]){  
Dog d=new Dog();  
d.work();  
}}  
• In the above example Animal and Dog both classes have eat() method
if we call eat() method from Dog class, it will call the eat() method of
Dog class by default because priority is given to local.
• To call the parent class method, we need to use super keyword.
super is used to invoke parent class constructor.

• The super keyword can also be used to invoke the


parent class constructor. Let's see a simple example:
class Animal{ 
 
Animal()
{System.out.println("animal is created");}  
}  
class Dog extends Animal{  
Dog()
{  
super();  
System.out.println("dog is created");  
}  
}  
class TestSuper3
{  
public static void main(String args[])
{  
Dog d=new Dog();  
}}  
Method Overriding in Java

• If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java.
• In other words, If a subclass provides the specific implementation of
the method that has been declared by one of its parent class, it is
known as method overriding.
Usage of Java Method Overriding

• Method overriding is used to provide the specific implementation of a


method which is already provided by its superclass.
• Method overriding is used for runtime polymorphism.
Rules for Java Method Overriding

• 1) The method must have the same name as in the parent class
• 2) The method must have the same parameter as in the parent class.
• 3) There must be an IS-A relationship (inheritance).
Java Program to illustrate the use of Java Method Overriding  
//Creating a parent class.  
class Vehicle{  
  //defining a method  
  void run(){System.out.println("Vehicle is running");}  
}  
//Creating a child class  
class Bike2 extends Vehicle{  
  //defining the same method as in the parent class  
  void run(){System.out.println("Bike is running safely");
}  
    public static void main(String args[]){  
  Bike2 obj = new Bike2();//creating object  
  obj.run();//calling method  
  }  
}  
Runtime Polymorphism in Java

• 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.
• In this process, an overridden method is called through the reference
variable of a superclass.
• The determination of the method to be called is based on the object
being referred to by the reference variable.
• When an overridden method is called through a superclass reference,
Java determines which version(superclass/subclasses) of that method
is to be executed based upon the type of the object being referred to
at the time the call occurs.
• Thus, this determination is made at run time.
• At run-time, it depends on the type of the object being referred to
(not the type of the reference variable) that determines which version
of an overridden method will be executed
• A superclass reference variable can refer to a subclass object. This is
also known as upcasting. Java uses this fact to resolve calls to
overridden methods at run time.
• Therefore, if a superclass contains a method that is overridden by a
subclass, then when different types of objects are referred to through
a superclass reference variable, different versions of the method are
executed.
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
 
}
class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
// obtain a reference of type A
A ref;
// ref refers to an A object
ref = a;
// calling A's version of m1()
ref.m1();
// now ref refers to a B object
ref = b;
// calling B's version of m1()
ref.m1();
// now ref refers to a C object
ref = c;
// calling C's version of m1()
ref.m1();
}
}
Output:
• Inside A's m1 method
• Inside B's m1 method
• Inside C's m1 method
Abstract class in Java

• A class which is declared as abstract is known as an abstract class.


• It can have abstract and non-abstract methods.
• It needs to be extended and its method implemented.
• It cannot be instantiated.(you cannot create new instance)
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.
Points to remember
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change
the body of the method.
Abstract Method in Java

• A method which is declared as abstract and does not have


implementation is known as an abstract method.
• Example of abstract method
• abstract void printStatus();//no method body and abstract 
Example of Abstract class that has an abstract method
In this example, Bike is an abstract class that contains only one abstract method
run. Its implementation is provided by the Honda class.
abstract class Bike{  
  abstract void run();  
}  
class Honda4 extends Bike{  
void run(){System.out.println("running safely");}  
public static void main(String args[]){  
 Bike obj = new Honda4();  
 obj.run();  
}  
}  
Final Keyword In Java

Using Final with Inheritance


• The keyword final has three uses. First, it can be used to create the
equivalent of a named constant.
• The other two uses of final apply to inheritance
Using final to Prevent Overriding

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.
The following fragment illustrates final:
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
• Because meth( ) is declared as final, it cannot be overridden in B. If
you attempt to do so, a compile-time error will result.
Using final to Prevent Inheritance

• To prevent a class from being inherited. Declaring a class as final


implicitly declares all of its methods as final, too.
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
Object class in Java

• The Object class is the parent class of all the classes in java by default.
• In other words, it is the topmost class of java.
Methods of Object
class

Method Description

public final Class getClass() returns the Class


class object of this
object. The Class class
can further be used to
get the metadata of this
The Object class provides many methods. They are as follows:
class.
public int hashCode() returns the hashcode number for
this object.
public boolean equals(Object compares the given object to this
obj) object.
Java package
• A java package is a group of similar types of classes, interfaces and
sub-packages.
• Package in java can be categorized in two form, built-in package and
user-defined package.
• There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.
• User Defined Package/Custom Package
• A Package which is created by the Programmer(User) is Known as
User defined package.
• To create the User defined package we use the package keyword.
• Syntax of Package Creation:-
•     package <package name>;
•     Ex:-
•          package p1;
Advantage of Java Package

• 1) Java package is used to categorize the classes and interfaces so that


they can be easily maintained.
• 2) Java package provides access protection.
• 3) Java package removes naming collision.
Simple example of java package

• The package keyword is used to create a package in


java.

//save as Simple.java  
package mypack;  
public class Simple{  
 
public static void main(String args[]){  
   
 System.out.println("Welcome to package");  
   
}  
}  
How to compile java package

• If you are not using any IDE, you need to follow


the syntax given below:

• javac -d directory javafilename  
• For example
• javac -d . Simple.java  
• The -d switch specifies the destination where to put the
generated class file. You can use any directory name like
/home (in case of Linux), d:/abc (in case of windows) etc. If
you want to keep the package within the same directory, you
can use . (dot).
How to run java package program

To Compile: javac -d . Simple.java

To Run: java mypack.Simple
How to access package from another
package?
• There are three ways to access the package from outside the package.
• import package.*;
• import package.classname;
• fully qualified name.
Using packagename.*

• If you use package.* then all the classes and interfaces of this package
will be accessible but not subpackages.
• The import keyword is used to make the classes and interface of
another package accessible to the current package.
Example of package that import the packagename.*
•//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();  }  
•}  
Using packagename.classname

• If you import package.classname then only declared class of this package will be accessible.
• Example of package by import package.classname
• //save by A.java  
•   
• package pack;  
• public class A{  
•   public void msg(){System.out.println("Hello");}  
• }  
• //save by B.java  
• package mypack;  
• import pack.A;  
•   
• class B{  
•   public static void main(String args[]){  
•    A obj = new A();  
•    obj.msg();  
•   }  
• }  
Using fully qualified name

• 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.
• It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.
//save by A.java  
package pack; 
 
public class A{  
  public void msg(){System.out.println("Hello");} 
 
}  
//save by B.java  
package mypack;
  
class B{
  
  public static void main(String args[]){ 
 
   pack.A obj = new pack.A();//
using fully qualified name  
   
obj.msg();  
  }  
Interface in Java

• 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.
• In other words, you can say that interfaces can have abstract methods
and variables. It cannot have a method body.Java Interface
also represents the IS-A relationship
• Why use Java interface?
• There are mainly three reasons to use interface. They are given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
• How to declare an interface?
• An interface is declared by using the interface keyword. It provides
total abstraction; means all the methods in an interface are declared
with the empty body, and all the fields are public, static and final by
default. A class that implements an interface must implement all the
methods declared in the interface
• Syntax:
• interface <interface_name>{  
•       
•     // declare constant fields  
•     // declare methods that abstract   
•     // by default.  
• }  
• In this example, the Printable interface has only one
method, and its implementation is provided in the A6
class.
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();  
 }  
}  
Interface inheritance

• A class implements an interface, but one interface extends another interface.


interface Printable{  
void print();  
}  
interface Showable extends Printable{  
void show();  
}  
class TestInterface4 implements Showable{  
public void print(){System.out.println("Hello");}  
public void show(){System.out.println("Welcome");}  
  
public static void main(String args[]){  
TestInterface4 obj = new TestInterface4();  
obj.print();  
obj.show();  
 }  
}  
Exception Handling in Java

• The Exception Handling in Java is one of the powerful mechanism to


handle the runtime errors so that normal flow of the application can
be maintained
• What is Exception in Java
• In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime
What is Exception Handling

• Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
• Hierarchy of Java Exception classes
• The java.lang.Throwable class is the root class of Java Exception
hierarchy which is inherited by two subclasses: Exception and Error. A
hierarchy of Java Exception classes are given below:
Difference between Checked and Unchecked Exceptions

1) Checked Exception
• The classes which directly inherit Throwable class except
RuntimeException and Error are known as checked exceptions e.g.
IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
• The classes which inherit RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.
3) Error
• Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Java Exception Keywords

try

catch

finally

throw

throws
try

• The "try" keyword is used to specify a block where we should place


exception code.
• The try block must be followed by either catch or finally. It means,
we can't use try block alone.
catch

• The "catch" block is used to handle the exception.


• It must be preceded by try block which means we can't use catch
block alone.
• It can be followed by finally block later.
finally

• The "finally" block is used to execute the important code of the


program.
• It is executed whether an exception is handled or not.
throw
• The "throw" keyword is used to throw an exception.
throws

• The "throws" keyword is used to declare exceptions.


• It doesn't throw an exception.
• It specifies that there may occur an exception in the method.
• It is always used with method signature.
Example of try-catch
• public class JavaExceptionExample{  
•   public static void main(String args[]){  
•    try{  
•       //code that may raise exception  
•       int data=100/0;  
•    }catch(ArithmeticException e){System.out.println(e);}  
•    //rest code of the program   
•    System.out.println("rest of the code...");  
•   }  
• }  
Output:
Exception in thread main java.lang.ArithmeticException:/ by zerorest of the code...
Java try block

• Java try block is used to enclose the code that might throw an


exception. It must be used within the method.
• If an exception occurs at the particular statement of try block, the rest
of the block code will not execute..
• Java try block must be followed by either catch or finally block.
• Syntax of Java try-catch
• try{    
• //code that may throw an exception    
• }catch(Exception_class_Name ref){}    
Syntax of try-finally block

• try{    
• //code that may throw an exception    
• }finally{}    
Java Multi-catch block

• 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.
• public class MultipleCatchBlock1 {  
•   
•     public static void main(String[] args) {  
•           
•            try{    
•                 int a[]=new int[5];    
•                 a[5]=30/0;    
•                }    
•               
• catch(ArithmeticException e)  
•                   {  
•                    System.out.println("Arithmetic Exception occurs");  
•                   }    
•                catch(ArrayIndexOutOfBoundsException e)  
•                   {  
•                    System.out.println("ArrayIndexOutOfBounds Exception occurs");  
•                   }    
•          
•       catch(Exception e)  
•                   {  
•                    System.out.println("Parent Exception occurs");  
•                   }             
•                System.out.println("rest of the code");    
•     }  
• }  
Java throw keyword

• The Java throw keyword is used to explicitly throw an


exception
• The syntax of java throw keyword is given below.
• throw exception;  
• public class TestThrow1{  
•    static void validate(int age){  
•      if(age<18)  
•       throw new ArithmeticException("not valid");  
•      else  
•       System.out.println("welcome to vote");  
•    }  
•    public static void main(String args[]){  
•       validate(13);  
•       System.out.println("rest of the code...");  
•   }  
• }  
Java throws keyword

• The Java throws keyword is used to declare an


exception.
• It gives an information to the programmer that there
may occur an exception so it is better for the
programmer to provide the exception handling code so
that normal flow can be maintained
Syntax of java throws
• return_type method_name() throws exception_class_
name
• {  
• //method code  
• }  
• import java.io.IOException;  
• class Testthrows1{  
•   void m()throws IOException{  
•     throw new IOException("device error");//checked exception  
•   }  
•   void n()throws IOException{  
•     m();  
•   }  
•   
• void p(){  
•    try{  
•     n();  
•    }catch(Exception e){System.out.println("exception handled");}  
•   }  
•   
• public static void main(String args[]){  
•    Testthrows1 obj=new Testthrows1();  
•    obj.p();  
•    System.out.println("normal flow...");  
•   }  
• }  
Java finally 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.
• Java finally block follows try or catch block.
• public class TestFinallyBlock2{  
•   public static void main(String args[]){  
•   try{  
•    int data=25/0;  
•    System.out.println(data);  
•   }  
•   catch(ArithmeticException e){System.out.println(e);}  
•   finally{System.out.println("finally block is always executed");}  
•   System.out.println("rest of the code...");  
•   }  
• }  
Java Custom Exception

• If you are creating your own Exception that is known as custom


exception or user-defined exception. Java custom exceptions are used
to customize the exception according to user need.
•class InvalidAgeException extends Exception{  
• InvalidAgeException(String s){  
•  super(s);  
• }  
•}  
•class TestCustomException1{  
•  
•   static void validate(int age)throws InvalidAgeException{  
•          
•    
• if(age<18)  
•       throw new InvalidAgeException("not valid");  
•      else  
•       System.out.println("welcome to vote");  
•    }  
• public static void main(String args[]){  
•       try{  
•       validate(13);  
•       }catch(Exception m){System.out.println("Exception occured: "+m);}  
•   
•       System.out.println("rest of the code...");  
•   }  
• }  

You might also like