Java Notes For Minor 2
Java Notes For Minor 2
Syntax :
class derived-class extends base-class
{
//methods and fields
}
Inheritance in Java Example
// concept of inheritance
// base class
class Bicycle {
this.gear = gear;
this.speed = speed;
speed -= decrement;
speed += increment;
}
// derived class
int startHeight)
super(gear, speed);
seatHeight = startHeight;
seatHeight = newValue;
// driver class
System.out.println(mb.toString());
Output
No of gears are 3
speed of bicycle is 100
seat height is 25
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.
import java.io.*;
class Employee {
// Driver Class
class Gfg {
Output
Salary : 60000
Benefits : 10000
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
import java.io.*;
import java.lang.*;
import java.util.*;
// Parent class
class one {
System.out.println("Geeks");
// Driver class
// Main function
g.print_geek();
g.print_for();
g.print_geek();
Output
Geeks
for
Geeks
2. Multilevel Inheritance
import java.io.*;
import java.lang.*;
import java.util.*;
class one {
System.out.println("Geeks");
}
class three extends two {
System.out.println("Geeks");
// Drived class
g.print_geek();
g.print_for();
g.print_geek();
Output
Geeks
for
Geeks
3. Hierarchical Inheritance
class A {
class B extends A {
class C extends A {
class D extends A {
}
// Driver Class
obj_B.print_A();
obj_B.print_B();
obj_C.print_A();
obj_C.print_C();
obj_D.print_A();
obj_D.print_D();
Output
Class A
Class B
Class A
Class C
Class A
Class D
Multiple Inheritance
import java.io.*;
import java.lang.*;
import java.util.*;
interface one {
interface two {
}
interface three extends one, two {
System.out.println("Geeks");
// Drived class
c.print_geek();
c.print_for();
c.print_geek();
Output
Geeks
for
Geeks
Hybrid Inheritance
}
Now, based on the above example, in Object-Oriented terms, the
following are true:-
class SolarSystem {
Output
true
true
true
What Can Be Done in a Subclass?
• 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.
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:
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
Test it Now
Output:
Vehicle is running
Test it Now
Output:
Bike is running safely
A real example of Java Method Overriding
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%)
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
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
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. //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. }
If you are not using any IDE, you need to follow the syntax given
below:
For example
1. javac -d . Simple.java
You need to use fully qualified name e.g. mypack.Simple etc to run
the class.
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.
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.
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
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.
Note: Sequence of the program must be package then import then class.
Subpackage in java
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. }
Output:Hello subpackage
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.
The -classpath switch can be used with javac and java tool.
• 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
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{}
In this tutorial, we will learn about Java exceptions, it's types, and
the difference between checked and unchecked exceptions.
Do You Know?
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
2) Unchecked Exception
3) Error
Java provides five keywords that are used to handle the exception.
The following table describes each.
Keyword Description
Test it Now
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
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 l
abeled as NORTH
13. JButton b2 = new JButton("SOUTH");; // the button will be l
abeled as SOUTH
14. JButton b3 = new JButton("EAST");; // the button will be lab
eled as EAST
15. JButton b4 = new JButton("WEST");; // the button will be la
beled as WEST
16. JButton b5 = new JButton("CENTER");; // the button will be
labeled as CENTER
17.
18. f.add(b1, BorderLayout.NORTH); // b1 will be placed in the N
orth Direction
19. f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the
South Direction
20. f.add(b3, BorderLayout.EAST); // b2 will be placed in the Ea
st 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 i
s 20
20. // and vertical gap is 15. The gap will be evident when button
s are placed
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: