Chapt 4
Chapt 4
Inheritance
Introduction
Inheritance is one of the OOP features
which is a form of software reuse in which a new class is created by absorbing an
existing class’s members, and embellishing them with new or modified
capabilities
When creating a class, rather than declaring completely new members, the
programmer can designate that the new class should inherit the members of an
existing class.
The existing class is called the Superclass, and the new class is the subclass.
Each subclass can become the superclass for future subclasses.
The subclass inherits the properties and methods from the superclass.
Conti….
Inheritance in java is an important and powerful feature in java
for reusing software, avoids redundancy and make the system
easy to comprehend and easy to maintain.
Java supports single inheritance, i.e., a class is derived from one
direct superclass. It does not support multiple inheritance (which
occurs when a class is derived from more than one direct
superclass).
extends keyword is used to inherit the properties of a
super class.
Syntax
• Example
Conti….
In the given program when an object to My_Calculation class is created, a copy of the
contents of the super class is made with in it. That is why, using the object of the
subclass you can access the members of a super class.
The Superclass reference variable can hold the subclass object, but using that
variable you can access only the members of the superclass, so to access the
members of both classes it is recommended to always create reference variable
from the subclass.
Conti….
Note:
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.
Its impossible to achieve encapsulation. Because constructors can initialized
the private members of the class.
Private members are only accessible in their own class. Can be accessible only
by public getter and setter methods of super class.
Constructors can invoke in sub class using super keyword.
IS-A Relationship:
IS-A is a way of saying: This object is a type of that object.
Example
instanceOf
operator is a java
keyword used to check
determine whether
Mammal is actually an
Animal, and dog is
actually an Animal
Has-A Relationship
These relationships are mainly based on the usage. This determines
whether a certain class HAS-A certain thing.
This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:
This shows that class Van HAS-A Speed. By having a separate class for
Speed, we do not have to put the entire code that belongs to speed inside
the Van class.
which makes it possible to reuse the Speed class in multiple applications.
Super keyword
the super keyword is used.
It is used to differentiate the members of super class from the members
of subclass, if they have same names.
it is used to invoke the superclass constructor from subclass.
The Syntax is
In the given program you have two classes namely Sub_class and
Super_class, both have a method named display with different
implementations, and a variable named num with different values.
•
• Output of the program:
• O|P is
Types of inheritance
Single Inheritance: refers to a child and parent class
relationship where a class extends the another class.
Multilevel inheritance: refers to a child and parent class
relationship where a class extends the child class. For example
class C extends class B and class B extends class A.
Hierarchical inheritance: refers to a child and parent class
relationship where more than one classes extends the same
class. For example, classes B, C & D extends the same class A.
Multiple Inheritance: refers to the concept of one class
extending more than one classes, which means a child class has
two parent classes. For example class C extends both classes A
and B. Java doesn’t support multiple inheritance. Implemented
using interface injava
•
The this keyword
Keyword this is a reference variable in java that refers to the
current object.
One of its common uses is to reference a class’s hidden data
fields.
The various usages of 'this' keyword in Java are as follows:
It can be used to refer instance variable of current class
It can be used to invoke or initiate current class constructor
It can be passed as an argument in the method call
It can be passed as argument in the constructor call
It can be used to return the current class instance
The this keyword
Example:
The this keyword gives us a way to refer to the object that invokes
an instance method within the code of the instance method.
The line this.i = i means “assign the value of parameter i to the
data field i of the calling object.”
The this keyword
Example2: class Account {
int a;
int b;
public void setData(int a ,int b){
a = a;
b = b;
}
public void showData(){
System.out.println("Value of A ="+a);
System.out.println("Value of B ="+b);
}
public static void main(String args[]){
Account obj = new Account();
obj.setData(2,3);
obj.showData();
}
}
The this keyword
Example2: class Account {
int a;
int b;
public void setData(int a ,int b){
a = a;
b = b;
}
public void showData(){
System.out.println("Value of A ="+a);
System.out.println("Value of B ="+b);
}
public static void main(String args[]){
Account obj = new Account();
obj.setData(2,3);
obj.showData();
}
}
• this Keyword with Constructor
• “this” keyword can be used inside the constructor to call another
overloaded constructor in the same Class.
• It is called the Explicit Constructor Invocation. This occurs if a
Class has two overloaded constructors, one without argument
and another with the argument. Then “this” keyword can be used
to call the constructor with an argument from the constructor
without argument. This is required as the constructor cannot be
called explicitly.
Note:
this keyword can only be the first statement in Constructor.
A constructor can have either this or super keyword but not
both.
class JavaB {
JavaB() {
this("JBT");
System.out.println("Inside Constructor without parameter");
}
JavaB(String str) {
System.out.println("Inside Constructor with String parameter as " + str);
}
public static void main(String[] args) {
JavaB obj = new JavaB();
}
}
what is the output?
this Keyword with Method
• this keyword can also be used inside Methods to call another
Method from same Class.
Question?
Chapter 5
Polymorphism
introduction
Polymorphism is one of the OOPs feature that allows us to perform
a single action in 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.
Polymorphism is the capability of a method to do different things
based on the object that it is acting upon.
For example Animal class can extend to Horse and Cat class
performing different actions.
Method Overloading and Overriding implements Polymorphism.
There are two types of polymorphism:
1) Static Polymorphism
2) Dynamic Polymorphism
Types of Polymorphism
Static Polymorphism: also known as compile time Polymorphism.
Polymorphism that is resolved during compiler time is known as static
polymorphism.
Method overloading is an example of compile time polymorphism.
Dynamic Polymorphism: also known as runtime polymorphism.
Dynamic polymorphism is a process in which a call to an overridden
method is resolved at runtime.
Example Method Overriding.
Method Overriding
Declaring a method in sub class which is already present in
parent class is known as method overriding.
The method in parent class is called overridden method and the
method in child class is called overriding method.
The method signature of subclass and super class is the same.
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
rule for method overriding
when you override a method remember the following point:
The method must have the same name as in the parent class
The method must have the same parameter list as in the parent class.
There must be an IS-A relationship (inheritance).
The return type should be the same or a subtype of the return type declared
in the original overridden method in the superclass.
The access level cannot be more restrictive than the overridden method’s
access level. For example: if the superclass method is declared public then
the overriding method in the sub class cannot be either private or protected.
A method declared final cannot be overridden.
A method declared static cannot be overridden. Because the static method is
bound with class whereas instance method is bound with an object. Static
belongs to the class.
If a method cannot be inherited, then it cannot be overridden.
Constructors cannot override.
Abstract Class
&
Interface
Abstract Class
What is abstraction in java?
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
focus on what the object does instead of how it does it. E.g., SMS message.
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract Class
A class which is declared with the abstract keyword is known as an abstract class.
It can have abstract and non-abstract methods (method with the body).
It can have constructors and static methods also.
It needs to be extended and its method implemented
It cannot be instantiated.
It can have final methods which will force the subclass not to change the body of the
method.
A class derived from the abstract class must implement all those methods that are
declared as abstract in the parent class.
Abstract Class conti….
Why can’t we create the object of an abstract class?
Since abstract class allows concrete methods as well, it does not
provide 100% abstraction.
You can say that it provides partial abstraction.
A class which is not abstract is referred as Concrete class.
You can’t have abstract method in a concrete class. It’s vice
versa is not always true: If a class is not having any abstract
method then also it can be marked as abstract.
An abstract class must be extended and in a same way abstract
method must be overridden.
Abstract methods are methods with out implementation.
Interface
An interface in java is a blueprint of a class.
An interface is used to implement full abstraction.
It has static constants and abstract methods.
An interface can have methods and variables just like the class but the
methods declared in interface are by default abstract.
Also, the variables declared in an interface are public, static & final by
default.
Since methods in interfaces do not have body, they have to be
implemented by the class before you can access them.
The class that implements interface must implement all the methods of
that interface.
Java programming language does not allow you to extend more than one
class, however you can implement more than one interfaces in your class.
Interface conti….
Interfaces are declared by specifying a keyword “interface”.
Syntax:
Output: Hello
Welcome
Key points you should remember about interface:
We can’t instantiate an interface in java. That means we
cannot create the object of an interface
Interface cannot be declared as private, protected or transient.
Interface variables must be initialized at the time of
declaration otherwise compiler will throw an error.
Class implements interface and interface extends interface.
A class cannot implement two interfaces that have methods
with same name but different return type.
Variable names conflicts can be resolved by interface name.
in general interface is used
When to use what?
Consider using abstract classes if any of these statements apply to your
situation:
In java application, there are some related classes that need to share some lines
of code then you can put these lines of code within abstract class and this
abstract class should be extended by all these related classes.
You can define non-static or non-final field(s) in abstract class, so that via a
method you can access and modify the state of Object to which they belong.
You can expect that the classes that extend an abstract class have many
common methods or fields, or require access modifiers other than public (such as
protected and private).
Consider using interfaces if any of these statements apply to your
situation:
It is total abstraction, all methods declared within an interface must be
implemented by the classes that implements this interface.
A class can implement more than one interface. It is called multiple inheritance.
You want to specify the behavior of a particular data type, but not concerned
about who implements its behavior.
Encapsulations
Encapsulation
Encapsulation simply means binding object state (fields) and
behavior (methods) together.
The whole idea behind encapsulation is to hide the
implementation details from users.
If a data member is private it means it can only be accessed
within the same class. No outside class can access private data
member (variable) of other class.
The private data fields outside class can access via public
methods.
How to implement encapsulation in java:
Make the instance variables private so that they cannot be accessed
directly from outside the class. You can only set and get values of these
variables through the methods of the class.
Have getter and setter methods in the class to set and get the values of
Advantage of Encapsulation
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
The users of a class do not know how the class stores its data. A
class can change the data type of a field and users of the class
do not need to change any of their code.
What is the difference between abstraction and
encapsulation while they both are hiding the
implementation from user?
Exception Handling
What is Exception Handling
What happen if we divide an integer number by zero?
What will happen if you try to access an array greater than its
size?
What happen if we try to access a null value of string type? ….
And so question how you try to handle?
The answer is to use exception handling
mechanisms in your code.
So, what is exception Handling?
Exception
An exception is an indication of a problem that occurs during a
program’s execution.
The name “exception” implies that the problem occurs
infrequently if the “rule” is that a statement normally executes
correctly, then the ”exception to the rule” is that a problem
occurs.
An exception can occur for many different reasons, below given
are some scenarios where exception occurs.
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of
communications or the JVM has run out of memory.
Exception Handling
Exception handling enables programmers to create
applications that can resolve (or handle) exceptions.
Exception handling enables programmers to remove error-
handling code from the “main line” of the program’s execution,
improving program clarity and enhancing modifiability.
With programming languages that do not support exception
handling, programmers often delay writing error-processing
code or sometimes forget to include it.
This results in less robust software products.
Java enables programmers to deal with exception handling
easily from the inception/ beginning of a project.
Exception Handling
In Java, runtime errors are caused by exceptions.
An exception is an object that represents an error or a condition that
prevents execution from proceeding normally.
If the exception is not handled, the program will terminate
abnormally.
There are three categories of Exceptions:
Checked exceptions: A checked exception is an exception that occurs at the
compile time, these are also called as compile time exceptions.
Unchecked exceptions: is an exception that occurs at the time of execution,
these are also called as Runtime Exceptions, and these include programming
bugs, such as logic errors or improper use of an API.
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.
catching Exception
A method catches an exception using a combination of the try and catch
keywords.
A try/catch block is placed around the code that might generate an
exception.
Syntax:
The try block contains the code that is executed in normal circumstances.
The catch block contains the code that is executed in exceptional
circumstances.
Exception handling separates error-handling code from normal
programming tasks, thus making programs easier to read and to modify.
Every try block should be immediately followed either by a catch block or
finally block.
The throws/throw Keywords:
If a method does not handle a checked exception, the method
must declare it using the throws keyword.
The throws keyword appears at the end of a method's signature.
The difference between throws and throw keywords, throws is
used to postpone the handling of a checked exception and throw
is used to invoke an exception explicitly.
Output
the finally block
Example
Outpu
t
the finally block
Flow of control in try/catch/finally blocks:
1) If exception occurs in try block’s body then control
immediately transferred(skipping rest of the statements
in try block) to the catch block. Once catch block finished
execution then finally block and after that rest of the
program.
2) If there is no exception occurred in the code which is present
in try block then first, the try block gets executed completely
and then control gets transferred to finally block (skipping
catch blocks).
3) If a return statement is encountered either in try or catch
block. In such case also finally runs. Control first goes to
finally and then it returned back to return statement.
the finally block
Note the following:
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses when ever a
try/catch block is present.
The try block cannot be present without either catch clause
or finally clause.
Any code cannot be present in between the try, catch, finally
blocks.
Question?
GUI
(Graphical User
Interface)
introduction
What is GUI?
It is another OOP constructing way.
i.e., The design of the API for Java GUI programming is an excellent
example of how the Object Oriented principle is applied.
GUI stands for Graphical User Interface, a term used not only
in java but in all programming languages that support the
development of GUIs.
It is made up of graphical components (e.g., buttons, labels,
windows) through which the user can interact with the page or
application.
A graphical user interface (GUI) presents a user-friendly
mechanism for interfacing with an application.
A GUI (pronounced “GOO-ee”) gives an application a distinctive
“look” and “feel” providing different applications with consistent,
intuitive user interface components allows users to be somewhat
familiar with an application, so that they can learn it more quickly
and use it more productively.
A GUI includes a range of user interface elements- which just
means all the elements that display when you are working in an
application. These can include:
Input control such as buttons, dropdown lists, checkboxes, and text
fields.
Informational elements such as labels, banners, icons, or notification
dialogs.
Navigational elements, including sidebars, breadcrumbs, and menus.
How it build?
GUIs are built from GUI components.
A GUI component is an object with which the user interacts via
the mouse, the keyboard or another form of input, such as
voice recognition.
Java GUI API
Currently there are three sets of Java APIs for graphics programming:
AWT(Abstract Windowing Toolkit), Swing and JavaFX.
1) AWT API was introduced in JDK 1.0. Most of the AWT components
have become obsolete and should be replaced by newer Swing
components.
2) Swing API, a much more comprehensive set of graphics libraries
that enhances the AWT, was introduced as part of Java Foundation
Classes (JFC) after the release of JDK 1.1. JFC consists of Swing,
Java2D, Accessibility, Internationalization, and Pluggable Look-and-
Feel Support APIs. JFC has been integrated into core Java since JDK
1.2.
3) The latest JavaFX, which was integrated into JDK 8, is meant to
replace Swing.
Java GUI API
The hierarchy of Java GUI component classes.
Java GUI API
Java GUI API contains classes that can be classified into three
groups: component classes, container classes, and helper
classes.
Component class is the root class for all GUI java classes.
The JFrame, JApplet, JDialog, and JComponent classes and
their subclasses are grouped in the javax.swing package.
All the other classes of AWT are grouped in the java.awt
package.
All Swing GUI components (except JFrame, JApplet, and
JDialog) are subclasses of Jcomponent.
The component classes
Component is the root class of all the user-interface classes
including container classes, and
JComponent is the root class of all the lightweight Swing
components.
An instance of Component can be displayed on the screen.
Both Component and JComponent are abstract classes.
Swing component classes (in package javax.swing) begin with
a prefix “J” e.g., JButton, JTextField, Jlabel, JPanel, JFrame, or
JApplet.
Method Description
There
public voidare component
add(Component c) class add
methods
a componentcommonly used in the
on another component.
program:
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.
The Container Classes
Container classes are GUI components that are used to
contain other GUI components.
Window, Panel, Applet, Frame, and Dialog are the
container classes for AWT components.
To work with Swing components, use Container, JFrame,
JDialog, JApplet, and JPanel.
GUI of swing Container Classes
Container Classes Description
java.awt.Container is used to group components. Frames, panels, and applets are its subclasses.
javax.swing.JFrame is a window not contained inside another window. It is used to hold other Swing
user-interface components in Java GUI applications.
javax.swing.JPanel is an invisible container that holds user-interface components. Panels can be
nested. You can place panels inside a container that includes a panel. JPanel is
also often used as a canvas to draw graphics.
javax.swing.JApplet is a subclass of Applet. You must extend JApplet to create a Swing-based Java
applet.
javax.swing.JDialog is a popup window or message box generally used as a temporary window to
receive additional information from the user or to provide notification that an
event has occurred.
GUI Helper Classes
The helper classes, such as Graphics, Color, Font,
FontMetrics, Dimension, and LayoutManager, are not
subclasses of Component.
They are used to describe the properties of GUI components,
such as graphics context, colors, fonts, and dimension.
The helper classes are in the java.awt package. The Swing
components do not replace all the classes in AWT.
The AWT helper classes are still useful in GUI programming.
Application Window Toolkit (AWT)
Java AWT (Abstract Window Toolkit) is an API to develop
GUI or window-based applications in java.
Java AWT components are platform-dependent.
AWT is heavyweight
There are two main AWT packages
- java.awt and java.awt.event - are commonly-used.
The java.awt package contains the core AWT graphics
classes:
GUI Component classes, such as Button, TextField, and Label.
GUI Container classes, such as Frame and Panel.
Layout managers, such
as FlowLayout, BorderLayout and GridLayout.
Custom graphics classes, such as Graphics, Color and Font.
AWT