Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
74 views

Java Notes

- Java inheritance allows classes to inherit features from other classes, enabling code reuse and extension of existing class functionality. There are different types of inheritance in Java including single, multilevel, hierarchical, and multiple (through interfaces). - Important terminology includes superclass/parent class, subclass/child class, and keywords like 'extends' and 'implements'. Inheritance supports concepts like abstraction, polymorphism, and code reusability. - Examples demonstrate how a subclass can inherit fields and methods from a superclass, while also adding its own fields and methods. This allows new classes to extend existing class functionality.

Uploaded by

Rohit Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
74 views

Java Notes

- Java inheritance allows classes to inherit features from other classes, enabling code reuse and extension of existing class functionality. There are different types of inheritance in Java including single, multilevel, hierarchical, and multiple (through interfaces). - Important terminology includes superclass/parent class, subclass/child class, and keywords like 'extends' and 'implements'. Inheritance supports concepts like abstraction, polymorphism, and code reusability. - Examples demonstrate how a subclass can inherit fields and methods from a superclass, while also adding its own fields and methods. This allows new classes to extend existing class functionality.

Uploaded by

Rohit Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Java

Unit 2&3 mix


 Inheritance in Java
Java, Inheritance is an important pillar of OOP(Object-Oriented
Programming). It is the mechanism in Java by which one class is allowed to
inherit the features(fields and methods) of another class. In Java,
Inheritance means creating new classes based on existing ones. A class that
inherits from another class can reuse the methods and fields of that class.
In addition, you can add new fields and methods to your current class as
well.

Why Do We Need Java Inheritance?


• Code Reusability: The code written in the Superclass is common to all
subclasses. Child classes can directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through Inheritance.
It is one of the ways by which Java achieves Run Time Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide all details
is achieved through inheritance. Abstraction only shows the functionality to the
user.

Important Terminologies Used in Java Inheritance


• Class: Class is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. Class is not a real-world entity. It is just a template
or blueprint or prototype from which objects are created.
• Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).
• Sub Class/Child Class: The class that inherits the other class is known as a
subclass(or a derived class, extended class, or child class). The subclass can add
its own fields and methods in addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want
to create a new class and there is already a class that includes some of the code
that we want, we can derive our new class from the existing class. By doing this,
we are reusing the fields and methods of the existing class.
How to Use Inheritance in Java?

The extends keyword is used for inheritance in Java. Using the extends
keyword indicates you are derived from an existing class. In other words,
“extends” refers to increased functionality.

Syntax :
class derived-class extends base-class
{
//methods and fields
}
Inheritance in Java Example

Example: In the below example of inheritance, class Bicycle is a base class,


class MountainBike is a derived class that extends the Bicycle class and
class Test is a driver class to run the program.
// Java program to illustrate the
// concept of inheritance

// base class
class Bicycle {
// the Bicycle class has two fields
public int gear;
public int speed;

// the Bicycle class has one constructor


public Bicycle(int gear, int speed)
{
this.gear = gear;
this.speed = speed;
}

// the Bicycle class has three methods


public void applyBrake(int decrement)
{
speed -= decrement;
}

public void speedUp(int increment)


{
speed += increment;
}

// toString() method to print info of Bicycle


public String toString()
{
return ("No of gears are " + gear + "\n"
+ "speed of bicycle is " + speed);
}
}

// derived class
class MountainBike extends Bicycle {

// the MountainBike subclass adds one more field


public int seatHeight;

// the MountainBike subclass has one constructor


public MountainBike(int gear, int speed,
int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}

// the MountainBike subclass adds one more method


public void setHeight(int newValue)
{
seatHeight = newValue;
}

// overriding toString() method


// of Bicycle to print more info
@Override public String toString()
{
return (super.toString() + "\nseat height is "
+ seatHeight);
}
}

// driver class
public class Test {
public static void main(String args[])
{

MountainBike mb = new MountainBike(3, 100, 25);


System.out.println(mb.toString());
}
}

Output
No of gears are 3
speed of bicycle is 100
seat height is 25
In the above program, when an object of MountainBike class is created, a
copy of all methods and fields of the superclass acquires memory in this
object. That is why by using the object of the subclass we can also access
the members of a superclass.
Please note that during inheritance only the object of the subclass is created,
not the superclass. For more, refer to Java Object Creation of Inherited
Class.
Example 2: In the below example of inheritance, class Employee is a base
class, class Engineer is a derived class that extends the Employee class and
class Test is a driver class to run the program.
// Java Program to illustrate Inheritance (concise)

import java.io.*;

// Base or Super Class


class Employee {
int salary = 60000;
}

// Inherited or Sub Class


class Engineer extends Employee {
int benefits = 10000;
}

// Driver Class
class Gfg {
public static void main(String args[])
{
Engineer E1 = new Engineer();
System.out.println("Salary : " + E1.salary
+ "\nBenefits : " + E1.benefits);
}
}

Output
Salary : 60000
Benefits : 10000

Illustrative image of the program:

In practice, inheritance, and polymorphism are used together in Java to


achieve fast performance and readability of code.

Java Inheritance Types

Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

1. Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. In the
image below, class A serves as a base class for the derived class B.

Single inheritance

// Java program to illustrate the


// concept of single inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

// Parent class
class one {
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one {


public void print_for() { System.out.println("for"); }
}

// Driver class
public class Main {
// Main function
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}

Output
Geeks
for
Geeks

2. Multilevel Inheritance

In Multilevel Inheritance, a derived class will be inheriting a base class, and as


well as the derived class also acts as the base class for other classes. In the
below image, class A serves as a base class for the derived class B, which in
turn serves as a base class for the derived class C. In Java, a class cannot
directly access the grandparent’s members.
Multilevel Inheritance

// Java program to illustrate the


// concept of Multilevel inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

class one {
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one {


public void print_for() { System.out.println("for"); }
}

class three extends two {


public void print_geek()
{
System.out.println("Geeks");
}
}

// Drived class
public class Main {
public static void main(String[] args)
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}

Output
Geeks
for
Geeks

3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for
more than one subclass. In the below image, class A serves as a base class
for the derived classes B, C, and D.
// Java program to illustrate the
// concept of Hierarchical inheritance

class A {
public void print_A() { System.out.println("Class A"); }
}

class B extends A {
public void print_B() { System.out.println("Class B"); }
}

class C extends A {
public void print_C() { System.out.println("Class C"); }
}

class D extends A {
public void print_D() { System.out.println("Class D"); }
}

// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();

C obj_C = new C();


obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();
obj_D.print_D();
}
}

Output
Class A
Class B
Class A
Class C
Class A
Class D

4. Multiple Inheritance (Through Interfaces)


In Multiple inheritances, one class can have more than one superclass and
inherit features from all parent classes. Please note that Java does not
support multiple inheritances with classes. In Java, we can achieve multiple
inheritances only through Interfaces. In the image below, Class C is derived
from interfaces A and B.
Multiple Inheritance

// Java program to illustrate the


// concept of Multiple inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

interface one {
public void print_geek();
}

interface two {
public void print_for();
}

interface three extends one, two {


public void print_geek();
}
class child implements three {
@Override public void print_geek()
{
System.out.println("Geeks");
}

public void print_for() { System.out.println("for"); }


}

// Drived class
public class Main {
public static void main(String[] args)
{
child c = new child();
c.print_geek();
c.print_for();
c.print_geek();
}
}

Output
Geeks
for
Geeks

5. Hybrid Inheritance(Through Interfaces)

It is a mix of two or more of the above types of inheritance. Since Java doesn’t
support multiple inheritances with classes, hybrid inheritance is also not
possible with classes. In Java, we can achieve hybrid inheritance only
through Interfaces.
Hybrid Inheritance

Java IS-A type of Relationship

IS-A is a way of saying: This object is a type of that object. Let us see how the
extends keyword is used to achieve inheritance.
public class SolarSystem {
}
public class Earth extends SolarSystem {
}
public class Mars extends SolarSystem {
}
public class Moon extends Earth {
}

Now, based on the above example, in Object-Oriented terms, the following


are true:-
• SolarSystem is the superclass of Earth class.
• SolarSystem is the superclass of Mars class.
• Earth and Mars are subclasses of SolarSystem class.
• Moon is the subclass of both Earth and SolarSystem classes.
class SolarSystem {
}
class Earth extends SolarSystem {
}
class Mars extends SolarSystem {
}
public class Moon extends Earth {
public static void main(String args[])
{
SolarSystem s = new SolarSystem();
Earth e = new Earth();
Mars m = new Mars();

System.out.println(s instanceof SolarSystem);


System.out.println(e instanceof Earth);
System.out.println(m instanceof SolarSystem);
}
}

Output
true
true
true
What Can Be Done in a Subclass?

In sub-classes we can inherit members as is, replace them, hide them, or


supplement them with new members:
• The inherited fields can be used directly, just like any other fields.
• We can declare new fields in the subclass that are not in the superclass.
• The inherited methods can be used directly as they are.
• We can write a new instance method in the subclass that has the same signature
as the one in the superclass, thus overriding it (as in the example above, toString()
method is overridden).
• We can write a new static method in the subclass that has the same signature as
the one in the superclass, thus hiding it.
• We can declare new methods in the subclass that are not in the superclass.
• We can write a subclass constructor that invokes the constructor of the
superclass, either implicitly or by using the keyword super.

Advantages Of Inheritance in Java:


1. 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.
2. 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.
3. Class Hierarchy: Inheritance allows for the creation of a class hierarchy, which
can be used to model real-world objects and their relationships.
4. Polymorphism: Inheritance allows for polymorphism, which is the ability of an
object to take on multiple forms. Subclasses can override the methods of the
superclass, which allows them to change their behavior in different ways.

Disadvantages of Inheritance in Java:


1. 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.
2. 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.

Conclusion

Let us check some important points from the article are mentioned below:
• 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.

Method Overriding in Java


1. Understanding the problem without method overriding
2. Can we override the static method
3. Method overloading vs. method overriding

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).
Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't
use method overriding.

1. //Java Program to demonstrate why we need method overriding


2. //Here, we are calling the method of parent class with child
3. //class object.
4. //Creating a parent class
5. class Vehicle{
6. void run(){System.out.println("Vehicle is running");}
7. }
8. //Creating a child class
9. class Bike extends Vehicle{
10. public static void main(String args[]){
11. //creating an instance of child class
12. Bike obj = new Bike();
13. //calling the method with child class instance
14. obj.run();
15. }
16. }

Test it Now

Output:
Vehicle is running

Problem is that I have to provide a specific implementation of run() method


in subclass that is why we use method overriding.

Example of method overriding


In this example, we have defined the run method in the subclass as defined
in the parent class but it has some specific implementation. The name and
parameter of the method are the same, and there is IS-A relationship
between the classes, so there is method overriding.
1. //Java Program to illustrate the use of Java Method Overriding
2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){System.out.println("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. obj.run();//calling method
15. }
16. }
Test it Now

Output:
Bike is running safely

A real example of Java Method Overriding


Consider a scenario where Bank is a class that provides functionality to get
the rate of interest. However, the rate of interest varies according to banks.
For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate
of interest.

Java method overriding is mostly used in Runtime Polymorphism which we will learn in
next pages.

1. //Java Program to demonstrate the real scenario of Java Method Overri


ding
2. //where three classes are overriding the method of a parent class.
3. //Creating a parent class.
4. class Bank{
5. int getRateOfInterest(){return 0;}
6. }
7. //Creating child classes.
8. class SBI extends Bank{
9. int getRateOfInterest(){return 8;}
10. }
11.
12. class ICICI extends Bank{
13. int getRateOfInterest(){return 7;}
14. }
15. class AXIS extends Bank{
16. int getRateOfInterest(){return 9;}
17. }
18. //Test class to create objects and call the methods
19. class Test2{
20. public static void main(String args[]){
21. SBI s=new SBI();
22. ICICI i=new ICICI();
23. AXIS a=new AXIS();
24. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
25. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());

26. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());


27. }
28. }

Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.

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.
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.
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.

Example of abstract class


1. abstract class A{}

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
1. 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.
1. abstract class Bike{
2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
Test it Now
running safely

Understanding the real scenario of Abstract class


In this example, Shape is the abstract class, and its implementation is provided by the
Rectangle and Circle classes.
Mostly, we don't know about the implementation class (which is hidden to the end
user), and an object of the implementation class is provided by the factory method.
A factory method is a method that returns the instance of the class. We will learn about
the factory method later.
In this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.
File: TestAbstraction1.java
1. abstract class Shape{
2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end use
r
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In a real scenario, object is provided through meth
od, e.g., getShape() method
15. s.draw();
16. }
17. }
Test it Now
drawing circle

Another example of Abstract class in java


File: TestBank.java
1. abstract class Bank{
2. abstract int getRateOfInterest();
3. }
4. class SBI extends Bank{
5. int getRateOfInterest(){return 7;}
6. }
7. class PNB extends Bank{
8. int getRateOfInterest(){return 8;}
9. }
10.
11. class TestBank{
12. public static void main(String args[]){
13. Bank b;
14. b=new SBI();
15. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
16. b=new PNB();
17. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
18. }}
Test it Now
Rate of Interest is: 7 %
Rate of Interest is: 8 %

Abstract class having constructor, data member and methods


(https://www.javatpoint.com/abstract-class-in-java)
An abstract class can have a data member, abstract method, method body (non-
abstract method), constructor, and even main() method.
File: TestAbstraction2.java
1. //Example of an abstract class that has abstract and non-abstract methods
2. abstract class Bike{
3. Bike(){System.out.println("bike is created");}
4. abstract void run();
5. void changeGear(){System.out.println("gear changed");}
6. }
7. //Creating a Child class which inherits Abstract class
8. class Honda extends Bike{
9. void run(){System.out.println("running safely..");}
10. }
11. //Creating a Test class which calls abstract and non-abstract methods
12. class TestAbstraction2{
13. public static void main(String args[]){
14. Bike obj = new Honda();
15. obj.run();
16. obj.changeGear();
17. }
18. }
Test it Now
bike is created
running safely..
gear changed

Rule: If there is an abstract method in a class, that class must be abstract.


1. class Bike12{
2. abstract void run();
3. }
Test it Now
compile time error
Rule: If you are extending an abstract class that has an abstract method, you must either
provide the implementation of the method or make this class abstract.

Another real scenario of abstract class


The abstract class can also be used to provide some implementation of the interface.
In such case, the end user may not be forced to override all the methods of the
interface.
Note: If you are beginner to java, learn interface first and skip this example.
1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am c");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}
Test it Now
Output: I am a
I am b
I am c
I am d

Java Package
(https://www.javatpoint.com/package)

1. Java Package
2. Example of package
3. Accessing package
1. By import packagename.*
2. By import packagename.classname
3. By fully qualified name
4. Subpackage
5. Sending class file to another directory
6. -classpath switch
7. 4 ways to load the class file or jar file
8. How to put two public class in a package
9. Static Import
10. Package class

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.

Here, we will have the detailed learning of creating and using user-defined
packages.

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.


1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename


For example
1. 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

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple


Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

How to access package from another package?

There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.

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.
Example of package that import the packagename.*

1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

2) 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

1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }

1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

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.

Example of package by import fully qualified name

1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello
Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be
imported excluding the classes and interfaces of the subpackages. Hence,
you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.

Subpackage in java

Package inside the package is called the subpackage. It should be created to


categorize the package further.

Let's take an example, Sun Microsystem has definded a package named java
that contains many classes like System, String, Reader, Writer, Socket etc.
These classes represent a particular group e.g. Reader and Writer classes
are for Input/Output operation, Socket and ServerSocket classes are for
networking etc and so on. So, Sun has subcategorized the java package into
subpackages such as lang, net, io etc. and put the Input/Output related
classes in io package, Server and ServerSocket classes in net packages and
so on.
The standard of defining package is domain.company.package e.g. com.javatpoint.bean
or org.sssit.dao.

Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }

To Compile: javac -d . Simple.java


To Run: java com.javatpoint.core.Simple
Output:Hello subpackage

How to send the class file to another directory or drive?

There is a scenario, I want to put the class file of A.java source file in classes
folder of c: drive. For example:

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
To Compile:

e:\sources> javac -d c:\classes Simple.java

To Run:

To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.

e:\sources> set classpath=c:\classes;.;

e:\sources> java mypack.Simple


Another way to run this program by -classpath switch of java:
The -classpath switch can be used with javac and java tool.

To run this program from e:\source directory, you can use -classpath switch
of java that tells where to look for class file. For example:

e:\sources> java -classpath c:\classes mypack.Simple


Output:Welcome to package

Ways to load the class files or jar files

There are two ways to load the class files temporary and permanent.

• Temporary
o By setting the classpath in the command prompt
o By -classpath switch
• Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar
file in the jre/lib/ext folder.

Rule: There can be only one public class in a java source file and it must be saved by the
public class name.

1. //save as C.java otherwise Compilte Time Error


2.
3. class A{}
4. class B{}
5. public class C{}

How to put two public classes in a package?

If you want to put two public classes in a package, have two java source files containing
one public class, but keep the package name same. For example:

1. //save as A.java
2.
3. package javatpoint;
4. public class A{}

1. //save as B.java
2.
3. package javatpoint;
4. public class B{}

Exception Handling in Java


1. Exception Handling
2. Advantage of Exception Handling
3. Hierarchy of Exception classes
4. Types of Exception
5. Exception Example
6. Scenarios where an exception may occur

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


the runtime errors so that the normal flow of the application can be
maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the
difference between checked and unchecked exceptions.
What is Exception in Java?

Dictionary Meaning: Exception is an abnormal condition.


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.
Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of


the application. An exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions. Let's consider a
scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there are 10 statements in a Java program and an exception occurs


at statement 5; the rest of the code will not be executed, i.e., statements
6 to 10 will not be executed. However, when we perform exception
handling, the rest of the statements will be executed. That is why we use
exception handling in Java.
Do You Know?
• What is the difference between checked and unchecked exceptions?
• What happens behind the code int data=50/0;?
• Why use multiple catch block?
• Is there any possibility when the finally block is not executed?
• What is exception propagation?
• What is the difference between the throw and throws keyword?
• What are the 4 rules for using exception handling with method overriding?

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy


inherited by two subclasses: Exception and Error. The hierarchy of Java
Exception classes is given below:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error
is considered as the unchecked exception. However, according to Oracle,
there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException
and Error are known as checked exceptions. For example, IOException,
SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked
exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Java Exception Keywords

Java provides five keywords that are used to handle the exception. The
following table describes each.

Keyword Description

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


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

The "catch" block is used to handle the exception. It must be preceded by try
catch block which means we can't use catch block alone. It can be followed by
finally block later.

The "finally" block is used to execute the necessary code of the program. It is
finally
executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

The "throws" keyword is used to declare exceptions. It specifies that there


throws may occur an exception in the method. It doesn't throw an exception. It is
always used with method signature.

Java Exception Handling Example

Let's see an example of Java Exception Handling in which we are using a try-
catch statement to handle the exception.

JavaExceptionExample.java
1. public class JavaExceptionExample{
2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }
Test it Now

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled


by a try-catch block.

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur.
They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.


1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the


variable throws a NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string variable that has
characters; converting this variable into digit will cause
NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


When an array exceeds to it's size, the ArrayIndexOutOfBoundsException
occurs. there may be other reasons to occur
ArrayIndexOutOfBoundsException. Consider the following statements.
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException

Java Exceptions Index


1. Java Try-Catch Block
2. Java Multiple Catch Block
3. Java Nested Try
4. Java Finally Block
5. Java Throw Keyword
6. Java Exception Propagation
7. Java Throws Keyword
8. Java Throw vs Throws
9. Java Final vs Finally vs Finalize
10. Java Exception Handling with Method Overriding
11. Java Custom Exceptions

AWT and Swing in Java


AWT and Swing are used to develop window-based applications in Java. Awt is an
abstract window toolkit that provides various component classes like Label, Button,
TextField, etc., to show window components on the screen. All these classes are part
of the Java.awt package.
On the other hand, Swing is the part of JFC (Java Foundation Classes) built on the top
of AWT and written entirely in Java. The javax.swing API provides all the component
classes like JButton, JTextField, JCheckbox, JMenu, etc.
The components of Swing are platform-independent, i.e., swing doesn't depend on the
operating system to show the components. Also, the Swing's components are
lightweight. The main differences between AWT and Swing are given in the following
table.
Context AWT Swing

The AWT Component classes The Swing component classes are


API Package are provided by the provided by the javax.swing
java.awt package. package.
The Components used in Swing
The Components used in AWT are not dependent on the
Operating System are mainly dependent on operating system. It is
the operating system. completely scripted in Java.

The Swing is mostly lightweight


since it doesn't need any
The AWT is heavyweight since Operating system object for
Weightiness it uses the resources of the processing. The Swing
operating system. Components are built on the
top of AWT.

The Appearance of AWT The Swing Components are


Components is mainly not configurable and mainly
Appearance configurable. It generally support pluggable look and
depends on the operating feel.
system's look and feels.
The Java AWT provides a Java Swing provides a greater
Number of smaller number of number of components than
Components components in comparison AWT, such as list, scroll panes,
to Swing. tables, color choosers, etc.

Java AWT stands for Abstract Java Swing is mainly referred to as


Full-Form Java Foundation Classes (JFC).
Window Toolkit.
Java Swing has only one peer in
Java AWT has 21 peers. There the form of OS's window
is one peer for each control object, which provides the
and one peer for the drawing surface used to draw
Peers dialogue. Peers are the Swing's widgets (label,
provided by the operating button, entry fields, etc.)
system in the form of developed directly by Java
widgets themselves. Swing Package.

Java AWT many features that Swing components provide the


are completely developed higher-level inbuilt functions
Functionality and by the developer. It serves for the developer that
Implementation as a thin layer of facilitates the coder to write
development on the top of less code.
the OS.
Java AWT needs a higher Java Swing needs less memory
Memory amount of memory for the space as compared to Java
execution. AWT.

Java AWT is slower than swing Java Swing is faster than the AWT.
Speed
in terms of performance.
Java Swing Hierarchy
Java defines the class hierarchy for all the Swing Components, which is shown in the
following image.

Java Swing Example


In the following example, we have created a User form by using the swing component
classes provided by the javax.swing package. Consider the example.
1. import javax.swing.*;
2. public class SwingApp {
3. SwingApp(){
4. JFrame f = new JFrame();
5.
6. JLabel firstName = new JLabel("First Name");
7. firstName.setBounds(20, 50, 80, 20);
8.
9. JLabel lastName = new JLabel("Last Name");
10. lastName.setBounds(20, 80, 80, 20);
11.
12. JLabel dob = new JLabel("Date of Birth");
13. dob.setBounds(20, 110, 80, 20);
14.
15. JTextField firstNameTF = new JTextField();
16. firstNameTF.setBounds(120, 50, 100, 20);
17.
18. JTextField lastNameTF = new JTextField();
19. lastNameTF.setBounds(120, 80, 100, 20);
20.
21. JTextField dobTF = new JTextField();
22. dobTF.setBounds(120, 110, 100, 20);
23.
24. JButton sbmt = new JButton("Submit");
25. sbmt.setBounds(20, 160, 100, 30);
26.
27. JButton reset = new JButton("Reset");
28. reset.setBounds(120,160,100,30);
29.
30. f.add(firstName);
31. f.add(lastName);
32. f.add(dob);
33. f.add(firstNameTF);
34. f.add(lastNameTF);
35. f.add(dobTF);
36. f.add(sbmt);
37. f.add(reset);
38.
39. f.setSize(300,300);
40. f.setLayout(null);
41. f.setVisible(true);
42. }
43.
44. public static void main(String[] args) {
45. // TODO Auto-generated method stub
46. SwingApp s = new SwingApp();
47. }
48. }
Output:

Java awt Example


To understand the differences between Awt and Swing, we have created the same
example in awt as well. Consider the following example.
1. import java.awt.*;
2. public class AwtApp extends Frame {
3. AwtApp(){
4. Label firstName = new Label("First Name");
5. firstName.setBounds(20, 50, 80, 20);
6.
7. Label lastName = new Label("Last Name");
8. lastName.setBounds(20, 80, 80, 20);
9.
10. Label dob = new Label("Date of Birth");
11. dob.setBounds(20, 110, 80, 20);
12.
13. TextField firstNameTF = new TextField();
14. firstNameTF.setBounds(120, 50, 100, 20);
15.
16. TextField lastNameTF = new TextField();
17. lastNameTF.setBounds(120, 80, 100, 20);
18.
19. TextField dobTF = new TextField();
20. dobTF.setBounds(120, 110, 100, 20);
21.
22. Button sbmt = new Button("Submit");
23. sbmt.setBounds(20, 160, 100, 30);
24.
25. Button reset = new Button("Reset");
26. reset.setBounds(120,160,100,30);
27.
28. add(firstName);
29. add(lastName);
30. add(dob);
31. add(firstNameTF);
32. add(lastNameTF);
33. add(dobTF);
34. add(sbmt);
35. add(reset);
36.
37. setSize(300,300);
38. setLayout(null);
39. setVisible(true);
40. }
41. public static void main(String[] args) {
42. // TODO Auto-generated method stub
43. AwtApp awt = new AwtApp();
44.
45. }
Output:
Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It is
notified against MouseEvent. The MouseListener interface is found in java.awt.event
package. It has five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);
Java MouseListener Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample extends Frame implements MouseListener{
4. Label l;
5. MouseListenerExample(){
6. addMouseListener(this);
7.
8. l=new Label();
9. l.setBounds(20,50,100,20);
10. add(l);
11. setSize(300,300);
12. setLayout(null);
13. setVisible(true);
14. }
15. public void mouseClicked(MouseEvent e) {
16. l.setText("Mouse Clicked");
17. }
18. public void mouseEntered(MouseEvent e) {
19. l.setText("Mouse Entered");
20. }
21. public void mouseExited(MouseEvent e) {
22. l.setText("Mouse Exited");
23. }
24. public void mousePressed(MouseEvent e) {
25. l.setText("Mouse Pressed");
26. }
27. public void mouseReleased(MouseEvent e) {
28. l.setText("Mouse Released");
29. }
30. public static void main(String[] args) {
31. new MouseListenerExample();
32. }
33. }
Output:

Java MouseListener Example 2


1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample2 extends Frame implements MouseListener{

4. MouseListenerExample2(){
5. addMouseListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseClicked(MouseEvent e) {
12. Graphics g=getGraphics();
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),30,30);
15. }
16. public void mouseEntered(MouseEvent e) {}
17. public void mouseExited(MouseEvent e) {}
18. public void mousePressed(MouseEvent e) {}
19. public void mouseReleased(MouseEvent e) {}
20.
21. public static void main(String[] args) {
22. new MouseListenerExample2();
23. }
24. }
Output:

Java ActionListener Interface


The Java ActionListener is notified whenever you click on the button or menu item. It is
notified against ActionEvent. The ActionListener interface is found in java.awt.event
package. It has only one method: actionPerformed().
actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the
registered component.
1. public abstract void actionPerformed(ActionEvent e);
How to write ActionListener
The common approach is to implement the ActionListener. If you implement the
ActionListener class, you need to follow 3 steps:
1) Implement the ActionListener interface in the class:
1. public class ActionListenerExample Implements ActionListener
2) Register the component with the Listener:
1. component.addActionListener(instanceOfListenerclass);
3) Override the actionPerformed() method:
1. public void actionPerformed(ActionEvent e){
2. //Write the code here
3. }
Java ActionListener Example: On Button click
1. import java.awt.*;
2. import java.awt.event.*;
3. //1st step
4. public class ActionListenerExample implements ActionListener{
5. public static void main(String[] args) {
6. Frame f=new Frame("ActionListener Example");
7. final TextField tf=new TextField();
8. tf.setBounds(50,50, 150,20);
9. Button b=new Button("Click Here");
10. b.setBounds(50,100,60,30);
11. //2nd step
12. b.addActionListener(this);
13. f.add(b);f.add(tf);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. //3rd step
19. public void actionPerformed(ActionEvent e){
20. tf.setText("Welcome to Javatpoint.");
21. }
22. }
Output:

Java ActionListener Example: Using Anonymous class


We can also use the anonymous class to implement the ActionListener. It is the
shorthand way, so you do not need to follow the 3 steps:
1. b.addActionListener(new ActionListener(){
2. public void actionPerformed(ActionEvent e){
3. tf.setText("Welcome to Javatpoint.");
4. }
5. });
Let us see the full code of ActionListener using anonymous class.
1. import java.awt.*;
2. import java.awt.event.*;
3. public class ActionListenerExample {
4. public static void main(String[] args) {
5. Frame f=new Frame("ActionListener Example");
6. final TextField tf=new TextField();
7. tf.setBounds(50,50, 150,20);
8. Button b=new Button("Click Here");
9. b.setBounds(50,100,60,30);
10.
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(ActionEvent e){
13. tf.setText("Welcome to Javatpoint.");
14. }
15. });
16. f.add(b);f.add(tf);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. }
Output:

Java MouseMotionListener
Interface
The Java MouseMotionListener is notified whenever you move or drag mouse. It is
notified against MouseEvent. The MouseMotionListener interface is found in
java.awt.event package. It has two methods.
Methods of MouseMotionListener interface
The signature of 2 methods found in MouseMotionListener interface are given below:
1. public abstract void mouseDragged(MouseEvent e);
2. public abstract void mouseMoved(MouseEvent e);
Java MouseMotionListener Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseMotionListenerExample extends Frame implements MouseM
otionListener{
4. MouseMotionListenerExample(){
5. addMouseMotionListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseDragged(MouseEvent e) {
12. Graphics g=getGraphics();
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),20,20);
15. }
16. public void mouseMoved(MouseEvent e) {}
17.
18. public static void main(String[] args) {
19. new MouseMotionListenerExample();
20. }
21. }
Output:
Java MouseMotionListener Example 2
1. import java.awt.*;
2. import java.awt.event.MouseEvent;
3. import java.awt.event.MouseMotionListener;
4. public class Paint extends Frame implements MouseMotionListener{
5. Label l;
6. Color c=Color.BLUE;
7. Paint(){
8. l=new Label();
9. l.setBounds(20,40,100,20);
10. add(l);
11.
12. addMouseMotionListener(this);
13.
14. setSize(400,400);
15. setLayout(null);
16. setVisible(true);
17. }
18. public void mouseDragged(MouseEvent e) {
19. l.setText("X="+e.getX()+", Y="+e.getY());
20. Graphics g=getGraphics();
21. g.setColor(Color.RED);
22. g.fillOval(e.getX(),e.getY(),20,20);
23. }
24. public void mouseMoved(MouseEvent e) {
25. l.setText("X="+e.getX()+", Y="+e.getY());
26. }
27. public static void main(String[] args) {
28. new Paint();
29. }
30. }
Output:
BorderLayout (LayoutManagers)
Java LayoutManagers
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. 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 etc.
Java BorderLayout
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:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
• BorderLayout(): creates a border layout but with no gaps between the

components.
• BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal

and vertical gaps between the components.


Example of BorderLayout class: Using BorderLayout() constructor
FileName: Border.java
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border
5. {
6. JFrame f;
7. Border()
8. {
9. f = new JFrame();
10.
11. // creating buttons
12. JButton b1 = new JButton("NORTH");; // the button will be labeled as NO
RTH
13. JButton b2 = new JButton("SOUTH");; // the button will be labeled as SO
UTH
14. JButton b3 = new JButton("EAST");; // the button will be labeled as EAST

15. JButton b4 = new JButton("WEST");; // the button will be labeled as WES


T
16. JButton b5 = new JButton("CENTER");; // the button will be labeled as CE
NTER
17.
18. f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Directi
on
19. f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Directi
on
20. f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction

21. f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction

22. f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center


23.
24. f.setSize(300, 300);
25. f.setVisible(true);
26. }
27. public static void main(String[] args) {
28. new Border();
29. }
30. }
Output:

download this example


Example of BorderLayout class: Using BorderLayout(int hgap, int vgap) constructor
The following example inserts horizontal and vertical gaps between buttons using the
parameterized constructor BorderLayout(int hgap, int gap)
FileName: BorderLayoutExample.java
1. // import statement
2. import java.awt.*;
3. import javax.swing.*;
4. public class BorderLayoutExample
5. {
6. JFrame jframe;
7. // constructor
8. BorderLayoutExample()
9. {
10. // creating a Frame
11. jframe = new JFrame();
12. // create buttons
13. JButton btn1 = new JButton("NORTH");
14. JButton btn2 = new JButton("SOUTH");
15. JButton btn3 = new JButton("EAST");
16. JButton btn4 = new JButton("WEST");
17. JButton btn5 = new JButton("CENTER");
18. // creating an object of the BorderLayout class using
19. // the parameterized constructor where the horizontal gap is 20
20. // and vertical gap is 15. The gap will be evident when buttons are place
d
21. // in the frame
22. jframe.setLayout(new BorderLayout(20, 15));
23. jframe.add(btn1, BorderLayout.NORTH);
24. jframe.add(btn2, BorderLayout.SOUTH);
25. jframe.add(btn3, BorderLayout.EAST);
26. jframe.add(btn4, BorderLayout.WEST);
27. jframe.add(btn5, BorderLayout.CENTER);
28. jframe.setSize(300,300);
29. jframe.setVisible(true);
30. }
31. // main method
32. public static void main(String argvs[])
33. {
34. new BorderLayoutExample();
35. }
36. }
Output:
Java BorderLayout: Without Specifying Region
The add() method of the JFrame class can work even when we do not specify the region.
In such a case, only the latest component added is shown in the frame, and all the
components added previously get discarded. The latest component covers the whole
area. The following example shows the same.
FileName: BorderLayoutWithoutRegionExample.java
1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class BorderLayoutWithoutRegionExample
6. {
7. JFrame jframe;
8.
9. // constructor
10. BorderLayoutWithoutRegionExample()
11. {
12. jframe = new JFrame();
13.
14. JButton btn1 = new JButton("NORTH");
15. JButton btn2 = new JButton("SOUTH");
16. JButton btn3 = new JButton("EAST");
17. JButton btn4 = new JButton("WEST");
18. JButton btn5 = new JButton("CENTER");
19.
20. // horizontal gap is 7, and the vertical gap is 7
21. // Since region is not specified, the gaps are of no use
22. jframe.setLayout(new BorderLayout(7, 7));
23.
24. // each button covers the whole area
25. // however, the btn5 is the latest button
26. // that is added to the frame; therefore, btn5
27. // is shown
28. jframe.add(btn1);
29. jframe.add(btn2);
30. jframe.add(btn3);
31. jframe.add(btn4);
32. jframe.add(btn5);
33.
34. jframe.setSize(300,300);
35. jframe.setVisible(true);
36. }
37.
38. // main method
39. public static void main(String argvs[])
40. {
41. new BorderLayoutWithoutRegionExample();
42. }
43. }
Output:

You might also like