The document outlines the syllabus and key concepts of Java inheritance, interfaces, and exception handling as taught by Ms. Sushma Malik. It covers definitions, types of inheritance, the use of the 'super' keyword, method overriding, and the differences between abstract classes and interfaces. Additionally, it discusses the advantages and disadvantages of inheritance and interfaces in Java programming.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
5 views111 pages
Unit 2-1
The document outlines the syllabus and key concepts of Java inheritance, interfaces, and exception handling as taught by Ms. Sushma Malik. It covers definitions, types of inheritance, the use of the 'super' keyword, method overriding, and the differences between abstract classes and interfaces. Additionally, it discusses the advantages and disadvantages of inheritance and interfaces in Java programming.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 111
BCA IV
Ms. Sushma Malik, Assistant Professor (IINTM)
Syllabus: Unit 2 Inheritance: Types, Super keyword, method overriding, covariant return type, abstract class. Interfaces and Packages: Creation and implementing an interface, difference between abstract class and interface, Packages, and importing a package. Exception Handling: Exception Class, built-in checked and unchecked exceptions, user-defined exceptions, use of try, catch, throw, throws, finally
Ms. Sushma Malik, Assistant Professor (IINTM)
Java - Inheritance Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. 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 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). Ms. Sushma Malik, Assistant Professor (IINTM) Java - Inheritance 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, also known as parent-child relationship.
Ms. Sushma Malik, Assistant Professor (IINTM)
Terms used in Inheritance Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. Ms. Sushma Malik, Assistant Professor (IINTM) Syntax of Java Inheritance
The extends keyword indicates that you are
making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. Ms. Sushma Malik, Assistant Professor (IINTM) Example of Inheritance
Ms. Sushma Malik, Assistant Professor (IINTM)
Types of inheritance in java On the basis of class, there can be three types of inheritance in java: Single, Multilevel Hierarchical.
Ms. Sushma Malik, Assistant Professor (IINTM)
Types of inheritance in java
Ms. Sushma Malik, Assistant Professor (IINTM)
Single Inheritance Example
Ms. Sushma Malik, Assistant Professor (IINTM)
Multilevel Inheritance Example
Ms. Sushma Malik, Assistant Professor (IINTM)
Hierarchical Inheritance Example
Ms. Sushma Malik, Assistant Professor (IINTM)
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 same method and you call it from child class object, there will be ambiguity to call 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 now.
Ms. Sushma Malik, Assistant Professor (IINTM)
Example
Ms. Sushma Malik, Assistant Professor (IINTM)
Important facts about inheritance in Java Default superclass: Except Object class, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of the Object class. Superclass can only be one: A superclass can have any number of subclasses. But a subclass can have only one superclass. This is because Java does not support multiple inheritances with classes. Although with interfaces, multiple inheritances are supported by java. Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. Private member inheritance: A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods(like getters and setters) for accessing its private fields, these can also be used by the subclass. Ms. Sushma Malik, Assistant Professor (IINTM) Advantages Of Inheritance in Java Code Reusability: Inheritance allows for code reuse and reduces the amount of code that needs to be written. The subclass can reuse the properties and methods of the superclass, reducing duplication of code. Abstraction: Inheritance allows for the creation of abstract classes that define a common interface for a group of related classes. This promotes abstraction and encapsulation, making the code easier to maintain and extend. Class Hierarchy: Inheritance allows for the creation of a class hierarchy, which can be used to model real-world objects and their relationships. Polymorphism: Inheritance allows for polymorphism, which is the ability of an object to take on multiple forms. Subclasses can override methods of the superclass, which allows them to change their behavior in different ways. Ms. Sushma Malik, Assistant Professor (IINTM) Disadvantages of Inheritance in Java
Complexity: Inheritance can make the code more
complex and harder to understand. This is especially true if the inheritance hierarchy is deep or if multiple inheritances is used. Tight Coupling: Inheritance creates a tight coupling between the superclass and subclass, making it difficult to make changes to the superclass without affecting the subclass.
Ms. Sushma Malik, Assistant Professor (IINTM)
super keyword in java The super keyword in Java is a reference variable that is used to refer to immediate parent class objects. Whenever you create the instance of a subclass, an instance of the parent class is created implicitly i.e. referred by the super reference variable.
Ms. Sushma Malik, Assistant Professor (IINTM)
Ms. Sushma Malik, Assistant Professor (IINTM) Characteristics of super keyword Super is used to call a superclass constructor: When a subclass is created, its constructor must call the constructor of its parent class. This is done using the super() keyword, which calls the constructor of the parent class. Super is used to call a superclass method: A subclass can call a method defined in its parent class using the super keyword. This is useful when the subclass wants to invoke the parent class’s implementation of the method in addition to its own. Super is used to access a superclass field: A subclass can access a field defined in its parent class using the super keyword. This is useful when the subclass wants to reference the parent class’s version of a field. Ms. Sushma Malik, Assistant Professor (IINTM) Characteristics of super keyword Super must be the first statement in a constructor: When calling a superclass constructor, the super() statement must be the first statement in the constructor of the subclass. Super cannot be used in a static context: The super keyword cannot be used in a static context, such as in a static method or a static variable initializer. Super is not required to call a superclass method: While it is possible to use the super keyword to call a method in the parent class, it is not required. If a method is not overridden in the subclass, then calling it without the super keyword will invoke the parent class’s implementation.
Ms. Sushma Malik, Assistant Professor (IINTM)
super is used to refer immediate parent class instance variable.
Ms. Sushma Malik, Assistant Professor (IINTM)
super can be used to invoke the parent class method
Ms. Sushma Malik, Assistant Professor (IINTM)
super is used to invoke the parent class constructor
Ms. Sushma Malik, Assistant Professor (IINTM)
super example: real use
Ms. Sushma Malik, Assistant Professor (IINTM)
Advantages of Super Keywords Enables reuse of code: Using the super keyword allows subclasses to inherit functionality from their parent classes, which promotes reuse of code and reduces duplication. Supports polymorphism: Because subclasses can override methods and access fields from their parent classes using super, polymorphism is possible. This allows for more flexible and extensible code. Provides access to parent class behavior: Subclasses can access and use methods and fields defined in their parent classes through the super keyword, which allows them to take advantage of existing behavior without having to reimplement it. Ms. Sushma Malik, Assistant Professor (IINTM) Advantages of Super Keywords Allows for customization of behavior: By overriding methods and using super to call the parent implementation, subclasses can customize and extend the behavior of their parent classes. Facilitates abstraction and encapsulation: The use of super promotes encapsulation and abstraction by allowing subclasses to focus on their own behavior while relying on the parent class to handle lower-level details.
Ms. Sushma Malik, Assistant Professor (IINTM)
Method Overriding in Java If the 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 provided by one of its parent classes, it is known as method overriding.
Ms. Sushma Malik, Assistant Professor (IINTM)
Usage of Java Method Overriding
Method overriding is used to provide specific
implementation of a method that is already provided by its super class. Method overriding is used for runtime polymorphism
Ms. Sushma Malik, Assistant Professor (IINTM)
Ms. Sushma Malik, Assistant Professor (IINTM) Understanding the problem without method overriding
Ms. Sushma Malik, Assistant Professor (IINTM)
Example of Method Overriding
Ms. Sushma Malik, Assistant Professor (IINTM)
Difference between Method Overloading and Method Overriding
Method Overloading Method Overriding
Method overloading is Method overriding is used to increase the used to provide the specific readability of the program. implementation of the Method overloading is method that is already performed within class. provided by its super class. In case of method Method overriding overloading, parameter occurs in two classes that must be different. have an IS-A (inheritance) Method overloading is the relationship. example of compile time In case of method polymorphism. overriding, the parameter must be the same. Method overriding is an example of run time polymorphism.
Ms. Sushma Malik, Assistant Professor (IINTM)
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 the method body. It is used to achieve abstraction and multiple inheritances 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. Ms. Sushma Malik, Assistant Professor (IINTM) Why use Java interface?
Ms. Sushma Malik, Assistant Professor (IINTM)
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.
Ms. Sushma Malik, Assistant Professor (IINTM)
How work interface? The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public, static and final keywords before data members.
Ms. Sushma Malik, Assistant Professor (IINTM)
The relationship between classes and interfaces
Ms. Sushma Malik, Assistant Professor (IINTM)
Difference Between Class and Interface
Ms. Sushma Malik, Assistant Professor (IINTM)
Java Interface Example
Ms. Sushma Malik, Assistant Professor (IINTM)
Java Interface Example: Drawable
Ms. Sushma Malik, Assistant Professor (IINTM)
Java Interface Example: Drawable The Drawable interface has only one method. Its implementation is provided by Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its implementation is provided by different implementation providers. Moreover, it is used by someone else. The implementation part is hidden by the user who uses the interface.
Ms. Sushma Malik, Assistant Professor (IINTM)
Java Interface Example: Bank
Ms. Sushma Malik, Assistant Professor (IINTM)
Multiple inheritance in Java by interface
Ms. Sushma Malik, Assistant Professor (IINTM)
Multiple inheritance in Java by interface
Ms. Sushma Malik, Assistant Professor (IINTM)
Multiple inheritance is not supported through class in java, but it is possible by an interface, why?
Ms. Sushma Malik, Assistant Professor (IINTM)
Multiple Inheritance in Java Multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class
Ms. Sushma Malik, Assistant Professor (IINTM)
Multiple Inheritance in Java
Ms. Sushma Malik, Assistant Professor (IINTM)
Interface inheritance
Ms. Sushma Malik, Assistant Professor (IINTM)
Why do we use an Interface? It is used to achieve total abstraction. Since java does not support multiple inheritances in the case of class, by using an interface it can achieve multiple inheritances. Any class can extend only 1 class but can any class implement infinite number of interface. It is also used to achieve loose coupling. Interfaces are used to implement abstraction.
Ms. Sushma Malik, Assistant Professor (IINTM)
Advantages of Interfaces in Java Without bothering about the implementation part, we can achieve the security of the implementation. In Java, multiple inheritances is not allowed, however, you can use an interface to make use of it as you can implement more than one interface.
Ms. Sushma Malik, Assistant Professor (IINTM)
Difference Between Abstract Class And Interface
Ms. Sushma Malik, Assistant Professor (IINTM)
Difference Between Abstract Class And Interface
Ms. Sushma Malik, Assistant Professor (IINTM)
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.
Ms. Sushma Malik, Assistant Professor (IINTM)
Advantage of Java Package Preventing naming conflicts. For example there can be two classes with name Employee in two packages, college.staff.cse.Employee and college.staff.ee.Employee Making searching/locating and usage of classes, interfaces, enumerations and annotations easier Providing controlled access: protected and default have package level access control. A protected member is accessible by classes in the same package and its subclasses. A default member (without any access specifier) is accessible by classes in the same package only. Packages can be considered as data encapsulation (or data- hiding). Ms. Sushma Malik, Assistant Professor (IINTM) Advantage of Java Package Reusability: While developing a project in java, we often feel that there are few things that we are writing again and again in our code. Using packages, you can create such things in form of classes inside a package and whenever you need to perform that same task, just import that package and use the class. Better Organization: Again, in large java projects where we have several hundreds of classes, it is always required to group the similar types of classes in a meaningful package name so that you can organize your project better and when you need something you can quickly locate it and use it, which improves the efficiency. Ms. Sushma Malik, Assistant Professor (IINTM) Types of packages
Ms. Sushma Malik, Assistant Professor (IINTM)
Built-in Packages These packages consist of a large number of classes which are a part of Java API.Some of the commonly used built-in packages are: java.lang: Contains language support classes(e.g classed which defines primitive data types, math operations). This package is automatically imported. java.io: Contains classed for supporting input / output operations. java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date / Time operations. java.applet: Contains classes for creating Applets. java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc). java.net: Contain classes for supporting networking operations. Ms. Sushma Malik, Assistant Professor (IINTM) User-defined packages These are the packages that are defined by the user. First we create a directory myPackage (name should be same as the name of the package). Then create the MyClass inside the directory with the first statement being the package names.
Sequence of the program must be package then import then class.
Ms. Sushma Malik, Assistant Professor (IINTM)
1) 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.
Ms. Sushma Malik, Assistant Professor (IINTM)
Example of package that import the packagename.*
Ms. Sushma Malik, Assistant Professor (IINTM)
2) Using packagename.classname If you import package.classname then only declared class of this package will be accessible.
Ms. Sushma Malik, Assistant Professor (IINTM)
3) 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.
Ms. Sushma Malik, Assistant Professor (IINTM)
Example of package by import fully qualified name
Ms. Sushma Malik, Assistant Professor (IINTM)
What is exception handling 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.
Exception Handling is a mechanism to handle runtime
errors such as ClassNotFound, IO, SQL, Remote etc.
Ms. Sushma Malik, Assistant Professor (IINTM)
What is exception
Dictionary Meaning: Exception is an abnormal
condition. In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
Ms. Sushma Malik, Assistant Professor (IINTM)
The core advantage of exception handling Advantage of Exception Handling
The core advantage of exception handling
is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application.
Ms. Sushma Malik, Assistant Professor (IINTM)
Hierarchy of Java Exception classes
Ms. Sushma Malik, Assistant Professor (IINTM)
Types of Exception
Ms. Sushma Malik, Assistant Professor (IINTM)
Checked Exception A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation, the programmer should take care of (handle) these exceptions. For example, if you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception.
Ms. Sushma Malik, Assistant Professor (IINTM)
Unchecked Exceptions An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
Ms. Sushma Malik, Assistant Professor (IINTM)
Errors These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
Ms. Sushma Malik, Assistant Professor (IINTM)
Common scenarios where exceptions may occur 1) Scenario where ArithmeticException occurs If we divide any number by zero, there occurs an ArithmeticException.
2) Scenario where NullPointerException occurs
If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.
Ms. Sushma Malik, Assistant Professor (IINTM)
Common scenarios where exceptions may occur 3) Scenario where NumberFormatException occurs The wrong formatting of any value, may occur NumberFormatException.
4) Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:
Ms. Sushma Malik, Assistant Professor (IINTM)
Java Exception Handling Keywords There are 5 keywords used in java exception handling. try catch finally throw throws
Ms. Sushma Malik, Assistant Professor (IINTM)
Java Exception Handling Keywords
Ms. Sushma Malik, Assistant Professor (IINTM)
Java try-catch Java try block is used to enclose the code that might throw an exception. It must be used within the method. Java try block must be followed by either catch or finally block.
Ms. Sushma Malik, Assistant Professor (IINTM)
Java catch block Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. Java catch block is used to handle the Exception. It must be used after the try block only. You can use multiple catch block with a single try.
Ms. Sushma Malik, Assistant Professor (IINTM)
Internal Working of Java try-catch block
Ms. Sushma Malik, Assistant Professor (IINTM)
Problem without exception handling
Ms. Sushma Malik, Assistant Professor (IINTM)
Solution by exception handling
Ms. Sushma Malik, Assistant Professor (IINTM)
Ms. Sushma Malik, Assistant Professor (IINTM) Java catch multiple exceptions
Ms. Sushma Malik, Assistant Professor (IINTM)
Ms. Sushma Malik, Assistant Professor (IINTM) Ms. Sushma Malik, Assistant Professor (IINTM) Java finally block Java finally block is a block used to execute important code such as closing the connection, etc. Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not. The finally block follows the try-catch block.
Ms. Sushma Malik, Assistant Professor (IINTM)
Java finally block
Ms. Sushma Malik, Assistant Professor (IINTM)
Why use Java finally block?
finally block in Java can be used to put
"cleanup" code such as closing a file, closing connection, etc. The important statements to be printed can be placed in the finally block.
Ms. Sushma Malik, Assistant Professor (IINTM)
Usage of Java finally Case 1: When an exception does not occur
Ms. Sushma Malik, Assistant Professor (IINTM)
Case 2: When an exception occur but not handled by the catch block
Ms. Sushma Malik, Assistant Professor (IINTM)
Java throw keyword The Java throw keyword is used to explicitly throw an exception. We can throw either checked or unchecked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. The syntax of java throw keyword is given below.
Ms. Sushma Malik, Assistant Professor (IINTM)
java throw keyword example (Throwing Unchecked Exception)
Ms. Sushma Malik, Assistant Professor (IINTM)
java throw keyword example (Throwing Unchecked Exception)
Ms. Sushma Malik, Assistant Professor (IINTM)
java throw keyword example (Throwing User-defined Exception)
Ms. Sushma Malik, Assistant Professor (IINTM)
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.
Ms. Sushma Malik, Assistant Professor (IINTM)
Java throws keyword
Which exception should be declared
Ans) checked exception only, because: unchecked Exception: under your control so correct your code. error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError or StackOverflowError.
Ms. Sushma Malik, Assistant Professor (IINTM)
Java throws Example
Ms. Sushma Malik, Assistant Professor (IINTM)
Java throws keyword There are two cases: 1. Case 1: We have caught the exception i.e. we have handled the exception using try/catch block. 2.Case 2: We have declared the exception i.e. specified throws keyword with the method.
Ms. Sushma Malik, Assistant Professor (IINTM)
Case 1: Handle Exception Using try-catch block
Ms. Sushma Malik, Assistant Professor (IINTM)
Case 2: Declare Exception
• In case we declare the exception if the exception
does not occur, the code will be executed fine. • In case we declare the exception and the exception occurs, it will be thrown at runtime because throws do not handle the exception.
Ms. Sushma Malik, Assistant Professor (IINTM)
A) If exception does not occur
Ms. Sushma Malik, Assistant Professor (IINTM)
B) If exception occurs
Ms. Sushma Malik, Assistant Professor (IINTM)
Difference between throw and throws in Java Basis of throw throws Differences
Definition Java throw keyword is used Java throws keyword is
throw an exception explicitly in used in the method the code, inside the function or signature to declare an the block of code. exception which might be thrown by the function while the execution of the code. Type of exception Using throw keyword, we can Using throws keyword, only propagate unchecked we can declare both exception i.e., the checked checked and unchecked exception cannot be propagated exceptions. However, the using throw only. throws keyword can be used to propagate checked exceptions only.
Ms. Sushma Malik, Assistant Professor (IINTM)
Difference between throw and throws in Java Basis of throw throws Differences
Syntax The throw keyword is followed The throws keyword is
by an instance of Exception to followed by class names be thrown. of Exceptions to be thrown.
Declaration throw is used within the method. throws is used with the method signature.
Internal We are allowed to throw only We can declare multiple
implementation one exception at a time i.e. we exceptions using throws cannot throw multiple keyword that can be exceptions. thrown by the method. For example, main() throws IOException, SQLException.