Java Notes
Java Notes
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
// base class
class Bicycle {
// the Bicycle class has two fields
public int gear;
public int speed;
// derived class
class MountainBike extends Bicycle {
// driver class
public class Test {
public static void main(String args[])
{
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.*;
// 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
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
// Parent class
class one {
public void print_geek()
{
System.out.println("Geeks");
}
}
// 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
class one {
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();
Output
Class A
Class B
Class A
Class C
Class A
Class D
interface one {
public void print_geek();
}
interface two {
public void print_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
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
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 {
}
Output
true
true
true
What Can Be Done in a 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.
If subclass (child class) has the same method as declared in the parent class,
it is known as method overriding in Java.
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.
Test it Now
Output:
Vehicle is running
Output:
Bike is running safely
Java method overriding is mostly used in Runtime Polymorphism which we will learn in
next pages.
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
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%)
• It cannot be instantiated.
• It can have final methods which will force the subclass not to change the body of
the method.
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
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.
1) Java package is used to categorize the classes and interfaces so that they
can be easily maintained.
If you are not using any IDE, you need to follow the syntax given below:
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
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.
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
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.
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
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. }
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:
To Run:
To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.
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:
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.
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{}
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;
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 "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.
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...
There are given some scenarios where unchecked exceptions may occur.
They are as follows:
1. String s=null;
2. System.out.println(s.length());//NullPointerException
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.
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 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