Java Unit-1 Revision
Java Unit-1 Revision
Constructors: When discussing about classes, one of the most important sub topic
would be constructors. Every class has a constructor. If we do not explicitly write a
constructor for a class the Java compiler builds a default constructor for that class.
• Each time a new object is created, at least one constructor will be invoked. The
main rule of constructors is that they should have the same name as the class. A
class can have more than one constructor. Example of a constructor is given
below:
Creating an Object
• A class provides the blueprints for objects. So basically an object is
created from a class. In Java, the new key word is used to create new
objects. There are three steps when creating an object from a class:
1. Declaration: A variable declaration with a variable name with an
object type. Instantiation: The 'new' key word is used to create the
object.
2. Initialization: The 'new' keyword is followed by a call to a
constructor. This call initializes the new object. Example of creating
an object is given below:
Revising Concepts
• Inheritance – Inheritance types- super keyword- preventing
inheritance: final classes and methods
• Polymorphism – method overloading and method overriding,
abstract classes and methods.
• Interface – Interfaces VS Abstract classes- defining an interface-
implement interfaces- accessing implementations through interface
references- extending interface -inner classes.
• Packages – Defining- creating and accessing a package- importing
packages.
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.
• Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
• The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
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.
In the terminology of Java, a class which is inherited is called a parent or superclass,
and the new class is called child or subclass.
Example:
Types of inheritance in java
• On the basis of class, there can be three types of inheritance in java:
single, multilevel and hierarchical.
• In java programming, multiple and hybrid inheritance is supported
through interface only.
Why multiple inheritance is not
supported in java?
• To reduce the complexity and simplify the language, multiple
inheritance is not supported in java.
• Consider a scenario where A, B, and C are three classes. The C class
inherits A and B classes. If A and B classes have the same method and
you call it from child class object, there will be ambiguity to call the
method of A or B class.
• Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have same
method or different, there will be compile time error.
Polymorphism
• Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.
Method Overloading
• If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
• If we have to perform only one operation, having same name of the methods
increases the readability of the program.
Advantage of method overloading
• Method overloading increases the readability of the program.
• Different ways to overload the method
There are two ways to overload the method in java
• By changing number of arguments
• By changing the data type
Method Overloading: changing no.
of arguments
• In this example, we have created two methods, first add() method
performs addition of two numbers and second add method performs
addition of three numbers.
Method Overloading: changing data
type of arguments
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
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).
Difference between method
overloading and method overriding
in java
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.
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.
Super can be used to refer immediate Super can be used to invoke parent
parent class instance variable. class method
Final Keyword
• The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
• variable
• method
• class
• The final keyword can be applied with the variables, a final variable
that have no value it is called blank final variable or uninitialized final
variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block
only. We will have detailed learning of these.
• 1) Java final variable
• If you make any variable as final, you cannot change the value of final
variable(It will be constant).
• Example of final variable
• There is a final variable speedlimit, we are going to change the value
of this variable, but It can't be changed because final variable once
assigned a value can never be changed.
2) Java final method
• If you make any method as final, you cannot override it.
• Example of final method
3) Java final class
• If you make any class as final, you cannot extend it.
• Example of final class
Abstraction
• 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.
• Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
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.
Example of Abstract class that has
an abstract method
Interface
• 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.
It cannot be instantiated just like the abstract class.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.
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.
Interface Declaraction:
The relationship between classes
and interfaces
• As shown in the figure given below, a class extends another class, an
interface extends another interface, but a class implements an
interface.
Example 1:
Example 2:
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an
interface extends multiple interfaces, it is known
as multiple inheritance.
Encapsulation
• Encapsulation in Java is a process of wrapping code and data
together into a single unit, for example, a capsule which is mixed of
several medicines.
• We can create a fully encapsulated class in Java by making all the data
members of the class private. Now we can use setter and getter
methods to set and get the data in it.
• The Java Bean class is the example of a fully encapsulated class.
Example of Encapsulation
Exception example:
Exception Handling
• Java exception handling is managed via five keywords: try, catch,
throw, throws, and finally.
How an exception is handled?
• We can also define our own set of conditions and throw an exception
explicitly using throw keyword. For example, we can throw
ArithmeticException if we divide a number by another number.
Exception
• Exception is an unwanted or unexpected event, which occurs during
the execution of a program, i.e. at run time, that disrupts the normal
flow of the program’s instructions. Exceptions can be caught and
handled by the program.
• When an exception occurs within a method, it creates an object. This
object is called the exception object. It contains information about
the exception, such as the name and description of the exception and
the state of the program when the exception occurred.
How Does JVM Handle an
Exception?
• Whenever inside a method, if an exception has occurred, the method creates an
Object known as an Exception Object and hands it off to the run-time system(JVM).
• The exception object contains the name and description of the exception and the
current state of the program where the exception has occurred.
• Creating the Exception Object and handling it in the run-time system is called
throwing an Exception. JVM is responsible for finding an exception handler tp
process the exception object.
• There might be a list of the methods that had been called to get to the method
where an exception occurred. This ordered list of methods is called Call Stack.
• The run-time system searches the call stack to find the method that contains a
block of code that can handle the occurred exception. The block of the code is
called an Exception handler.
1. Built-in Exceptions
• Built-in exceptions are the exceptions that are available in Java libraries.
• Checked Exceptions: Checked exceptions are called compile-time
exceptions because these exceptions are checked at compile-time by
the compiler.
}
throw keyword
• Java throw keyword is used to throw an exception explicitly.
• We specify the exception object which is to be thrown. The Exception
has some message with it that provides the error description. These
exceptions may be related to user inputs, server, etc.
• We can throw either checked or unchecked exceptions in Java by
throw keyword. It is mainly used to throw a custom exception.
Throwing an Exception
throws keyword
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used
Simple Applet
An Applet Skelton
AWT UI Components
• Component class
Component class is at the top of AWT hierarchy. It is an abstract class
that encapsulates all the attributes of visual component. A component
object is responsible for remembering the current foreground and
background colors and the currently selected text font.
• Container
Container is a component in AWT that contains another component
like button, text field, tables etc. Container is a subclass of component
class. Container class keeps track of components that are added to
another component.
• Panel
Panel class is a concrete subclass of Container. Panel does not contain
title bar, menu bar or border. It is container that is used for holding
components.
• Window class
Window class creates a top level window. Window does not have
borders and menubar.
• Frame
Frame is a subclass of Window and have resizing canvas. It is a
container that contain several different components like button, title
bar, textfield, label etc. In Java, most of the AWT applications are
created using Frame window. Frame class has two different
constructors,
Useful Methods of Component Class
To create simple AWT example, you need a frame. There are two ways
to create a GUI using Frame in AWT.
• By extending Frame class (inheritance)
• By creating the object of Frame class (association)
By extending Frame class (inheritance)
By creating the object of Frame class (association)
AWT Button
• In Java, AWT contains a Button Class. It is used for creating a labelled button which can perform an
action.
• create a button and it to the frame by providing coordinates.
import java.awt.*;
public class ButtonDemo1
{
public static void main(String[] args)
{
Frame f1=new Frame("studytonight ==> Button Demo");
Button b1=new Button("Press Here");
b1.setBounds(80,200,80,50);
f1.add(b1);
f1.setSize(500,500);
f1.setLayout(null);
f1.setVisible(true);
}
}
AWT Label
• In Java, AWT contains a Label Class. It is used for placing text in a container. Only Single line text is allowed and the text
can not be changed directly.
• creating two labels to display text to the frame.
import java.awt.*;
class LabelDemo1
{
public static void main(String args[])
{
Frame l_Frame= new Frame("studytonight ==> Label Demo");
Label lab1,lab2;
lab1=new Label("Welcome to studytonight.com");
lab1.setBounds(50,50,200,30);
lab2=new Label("This Tutorial is of Java");
lab2.setBounds(50,100,200,30);
l_Frame.add(lab1);
l_Frame.add(lab2);
l_Frame.setSize(500,500);
l_Frame.setLayout(null);
l_Frame.setVisible(true);
AWT TextField
• WT contains aTextField Class. It is used for displaying single line text.
• creating two textfields to display single line text string.
import java.awt.*;
class TextFieldDemo1{
public static void main(String args[]){
Frame TextF_f= new Frame("studytonight ==>TextField");
TextField text1,text2;
text1=new TextField("Welcome to studytonight");
text1.setBounds(60,100, 230,40);
text2=new TextField("This tutorial is of Java");
text2.setBounds(60,150, 230,40);
TextF_f.add(text1);
TextF_f.add(text2);
TextF_f.setSize(500,500);
TextF_f.setLayout(null);
TextF_f.setVisible(true);
}
AWT TextArea
• AWT contains aTextArea Class. It is used for displaying multiple-line text.
• creating a TextArea that is used to display multiple-line text string and allows text editing as well.
import java.awt.*;
public class TextAreaDemo1
{
TextAreaDemo1()
{
Frame textArea_f= new Frame();
TextArea area=new TextArea("Welcome to studytonight.com");
area.setBounds(30,40, 200,200);
textArea_f.add(area);
textArea_f.setSize(300,300);
textArea_f.setLayout(null);
textArea_f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaDemo1();
}
}
AWT Checkbox
• AWT contains a Checkbox Class. It is used when we want to select
only one option i.e true or false. When the checkbox is checked then
its state is "on" (true) else it is "off"(false).
• creating checkbox that are used to get user input. If checkbox is
checked it returns true else returns false.
import java.awt.*;
public class CheckboxDemo1
{
CheckboxDemo1(){
Frame checkB_f= new Frame("studytonight ==>Checkbox Example");
Checkbox ckbox1 = new Checkbox("Yes", true);
ckbox1.setBounds(100,100, 60,60);
Checkbox ckbox2 = new Checkbox("No");
ckbox2.setBounds(100,150, 60,60);
checkB_f.add(ckbox1);
checkB_f.add(ckbox2);
checkB_f.setSize(400,400);
checkB_f.setLayout(null);
checkB_f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxDemo1();
}
}
AWT Choice
• AWT contains a Choice Class. It is used for creating a drop-down menu
of choices. When a user selects a particular item from the drop-down
then it is shown on the top of the menu.
• creating drop-down menu that is used to get user choice from
multiple choices.
import java.awt.*;
public class ChoiceDemo
{
ChoiceDemo()
{
Frame choice_f= new Frame();
Choice obj=new Choice();
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
choice_f.add(obj);
choice_f.setSize(400,400);
choice_f.setLayout(null);
choice_f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceDemo();
}
AWT List
• AWT contains a List Class. It is used to represent a list of items
together. One or more than one item can be selected from the list.
• creating a list that is used to list out the items.
import java.awt.*;
public class ListDemo
{
ListDemo()
{
Frame list_f= new Frame();
List obj=new List(6);
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
list_f.add(obj);
list_f.setSize(400,400);
list_f.setLayout(null);
list_f.setVisible(true);
}
public static void main(String args[])
{
new ListDemo();
}
Swings
• Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used
to create window-based applications. It is built on the top of AWT
(Abstract Windowing Toolkit) API and entirely written in java.
• Unlike AWT, Java Swing provides platform-independent and lightweight
components.
• The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
• Swing is a Java Foundation Classes [JFC] library and an extension of the
Abstract Window Toolkit [AWT]. Swing offers much-improved
functionality over AWT, new components, expanded components
features, and excellent event handling with drag-and-drop support.
Introduction to Swing framework
• Java Swing is a GUI toolkit and a part of JFC (Java Foundation Class)
helpful in developing window-based applications.
• Java Swing is lightweight and platform-independent that contains
various components and container classes.
• Furthermore, the Java swing library is built on the top of the
AWT(Abstract Window Toolkit), an API completely written in Java.
• In every application, users can find an interactive and user-friendly
interface that gives them the freedom to use the app.
Swing Components
• Swing components are the fundamental building blocks of an
application. Swing has various components, including buttons,
checkboxes, sliders, and list boxes. In this part of the Swing tutorial,
we will present JButton, JLabel, JTextField, and JPasswordField.
function of Swing components in Java
• Swing in java is part of the Java foundation class, which is lightweight
and platform-independent. It is used for creating window-based
applications.
Difference between Swing and
AWT components
Swing and AWT are the two toolkits for building interactive Graphical
User Interfaces (GUI).
The critical difference between Swing and AWT in Java is that AWT is
Java's conventional platform-dependent graphics and user interface
widget toolkit. In contrast, Swing is a GUI widget toolkit for Java, an
AWT extension.
Hierarchy of Java Swing classes
Example 1: Develop a program using label
(swing) to display message “Java is Amazing”;
import java.io.*;
import javax.swing.*;
class ABC {
public static void main(String[] args)
{
JFrame frame= new JFrame();
JButton button = new JButton(" Java is Amazing");
button.setBounds(150, 200, 220,50);
frame.add(button);
frame.setSize(500, 600);
frame.setLayout(null);
frame.setVisible(true);
}
}
Example 2: Write a program to create three
buttons with caption OK , SUBMIT, CANCLE.
import java.awt.*;
class button {
button() {
Frame f = new Frame();
Button b1 = new Button("OK");
b1.setBounds(100, 50, 50, 50);
f.add(b1);
Button b2 = new Button("SUBMIT");
b2.setBounds(100, 101, 50, 50);
f.add(b2);
Button b3 = new Button("CANCLE");
b3.setBounds(100, 150, 80, 50);
f.add(b3);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String a[]) {
new button();
}
}
SWING UI Elements
Swing Features
• Light Weight − Swing components are independent of native
Operating System's API as Swing API controls are rendered mostly
using pure JAVA code instead of underlying operating system calls.
• Rich Controls − Swing provides a rich set of advanced controls like
Tree, TabbedPane, slider, colorpicker, and table controls.
• Highly Customizable − Swing controls can be customized in a very
easy way as visual apperance is independent of internal
representation.
• Pluggable look-and-feel − SWING based GUI Application look and feel
can be changed at run-time, based on available values.
Java Jframe:
• The javax.swing.JFrame class is a type of container which inherits the
java.awt.Frame class. JFrame works like the main window where
components like labels, buttons, textfields are added to create a GUI.
• Unlike Frame, JFrame has the option to hide or close the window with
the help of setDefaultCloseOperation(int) method.
setDefaultCloseOperation():
The setDefaultCloseOperation() method is used to specify one of several options for the
close button. Use one of the following constants to specify your choice:
f.add(b);
f.add(t);
b.addActionListener(this); Registration
}
Public void actionPerformed(ActionEvent ae){
String s=ae.getActionCommand();
t.setText(s);
}
Public static void main(String[] args){
eventExample ex=new eventExample();
}
ItemListener
• Used for radioButton, List,Choice, and Checkbox.
• Override public void itemStateChanged(ItemEvent e)
}
}
Example: WAP to create a frame. Place 3 buttons: yes, no , maybe
and prints a message for the same using ActionEvent.
Practice Q1:Print message on button
ActionEvent
Practice Q2:Basic Calculator
Layout Managers
• The LayoutManagers are used to arrange components in a particular manner.
• The Java LayoutManagers facilitates us to control the positioning and size of
the components in GUI forms.
• LayoutManager is an interface that is implemented by all the classes of layout
managers.
• The layout manager automatically positions all the components within the
container. Even if you do not use the layout manager, the components are still
positioned by the default layout manager.
• Java provides various layout managers to position the controls. Properties like
size, shape, and arrangement varies from one layout manager to the other.
When the size of the applet or the application window changes, the size,
shape, and arrangement of the components also changes in response, i.e. the
layout managers adapt to the dimensions of the appletviewer or the
application window.
There are the following classes that
represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout
Java BorderLayout Class
• The BorderLayout is used to arrange the components in five regions:
north, south, east, west, and center. Each region (area) may contain
one component only. It is the default layout of a frame or window.
• The BorderLayout provides five constants for each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
• BorderLayout(): creates a border layout but with no gaps between the
components.
Example of BorderLayout class: Using BorderLayout() constructor