Java Unit-2
Inheritance: Super and subclasses; visibility modifiers; Types of Inheritance-
single, multiple, hierarchical and hybrid inheritance; the interface concept in
Java, Polymorphism: Compile time and run time polymorphisms – Method
overloading and method overriding. Package: Types of packages; the util,
awt and swing packages; Creating and importing user-defined packages. I/O
programming: Standard I/O streams in Java; Types of streams – Base3d on
the type of Operations and the type of file.
Inheritance in Java
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
Super Class: The class whose features are inherited is known as super
class(or a base class or a parent class).
Sub Class: The class that inherits the other class is known as sub class(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.
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. We will learn about interfaces later.
Types of inheritance in Java
Understanding Inheritance
Class X {
int I;
void functionx() {
[Link]("in super class I=" +I) ;
// [Link](" In super class j=" +j) ; //error
}
}
Class Y extends X { Output
Int j; In subclass j=20
void functiony() { In subclass I=30
[Link](" In subclass j=" +j) ;
[Link](" In superclass I="+I) ; In super class I=30
}
Public static void main(String args[]) {
Y a1=new Y() ;
a1.j=20;
a1.i=30;
[Link]() ;
[Link]() ;
}
}
(out of syllabus)Here Y a1=new Y() ; creates the object for the class Y.
and it loads all the instance variables(non static variables) inside the
object by calling constructor. While executing the contructor, it first
searches whether class Y extends any other class or not. Yes the class Y
extends class X, so it's creates an object for the class X in association
with object of class Y, and starts executing constructor of class X.
I=0
Address of
functionx()
Y1 J=0
Address of
functiony()
Now the control is in constructor of class X and here also it
searches whether class X is extending any other class or not. If
yes the same process as above repeats. If no, the control
executes the statement of constructor of class Xand now object
of class X is created completely.
Once the execution of class X is over, then it reaches back to the
calling place( constructor of class Y) executes the statements
inside the constructor and now object of class Y is created
completely.
1. Whenever we create an object of subclass, then super class
object will also be created automatically.
2. The object of superclass is created first and then the obejct
of the subclass
3. Super class object is created from the constructor of the
subclass
4. Superclass object is cretaed in association with sub class
object.
y1.j=20;
Jvm searches for variable j inside the object of class Y. Since it is
found, the value of variable j inside object of class Y pointed by y1
changes from 0 to 20.
Next statement is
y1.i=30;
Now jvm searches for variable I inside the object of class Y. Since it
does not find it . It searches for i in the immediate super class
object which is associated with the sub class object. It finds the
variable I it changes it's value to 30.
Similarly when the statement [Link] () is executed, jvm
searches whether functiony() address is present inside object of
class Y or not. Since it is present, it executes the functiony()
method of class Y.
When we execute the statement y1. functionx(), JVM searches for
the address of this method in class Y object. Since it is not found, it
searches in the class X object. Since it is found, it executes the
functionx() method of class X.
Types of inheritance (and its Examples)
a. Multilevel Inheritance: A class extending another class as in hierarchical
structure is termed as multilevel inheritance.
Eg: class A {
int x,y;
method1( )
}
class B extends A{
int i, j;
method2( )
}
class C extends B {
int a,b;
method3( )
}
b. Single Inheritance : A class extends from another class.
Eg: class A {
int x,y;
method1( )
}
class B extends A{
int i, j;
method2( )
}
Single inheritance .When a class extends another one class only then we call it
a single inheritance
Single Inheritance example program in Java
Class A
{
public void methodA()
{
[Link]("Base class method");
}
}
Class B extends A
{
public void methodB()
{
[Link]("Child class method");
}
public static void main(String args[])
{
B obj = new B();
[Link](); //calling super class method
[Link](); //calling local method
}
}
Multilevel inheritance refers to a mechanism where one can inherit from a derived class, thereby
making this derived class the base class for the new class.
Class X
{
public void methodX()
{
[Link]("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
[Link]("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
[Link]("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
[Link](); //calling grand parent class method
[Link](); //calling parent class method
[Link](); //calling local method
}
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.
class Animal{
void eat(){
[Link]("eating...");}
}
class Dog extends Animal{
void bark(){
[Link]("barking...");}
}
class Cat extends Animal{
void meow(){
[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}
Hybrid Inheritance
It is a mix of two or more of all the other
types of inheritance.
It can be achieved through a combination of
Multilevel Inheritance and Hierarchical
Inheritance with classes, Hierarchical and
Single Inheritance with classes.
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.
Polymorphism in Java is one of the core concepts in object-oriented programming
(OOP) that allows objects to behave differently based on their specific class type. The word
polymorphism means having many forms, and it comes from the Greek words poly (many) and
morph (forms). This means one entity can take many forms.
•Multiple Behaviors: The same method can behave differently depending on the object that
calls this method.
•Method Overriding: A child class can redefine a method of its parent class.
•Method Overloading: We can define multiple methods with the same name but different
parameters.
•Runtime Decision: At runtime, Java determines which method to call depending on the
object's actual class.
1. Compile-Time Polymorphism
Compile-Time Polymorphism in Java, also known as static polymorphism, is achieved
mainly through method overloading, where multiple methods with the same name exist
but differ in parameter lists. The method to be called is resolved by the compiler at
compile time.
Method Overloading
Method overloading means defining multiple methods with the same name but different
parameter lists. The method call is resolved at compile time based on the arguments
passed.
Method Overloading
import [Link];
public class AddNumbersOverloading {
// Method to add two integers
public static int add(int a, int b) {
return a + b;
}
// Method to add two double values
public static double add(double a, double b) {
return a + b;
}
// Method to add three integers
public static int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
[Link]("Sum of three integers: " + add(11,11));
[Link]("Sum of three integers: " + add(11.4, 12.6));
[Link]("Sum of three integers: " + add(11,7, 12));
[Link]("Invalid input. Please enter numeric values only.");
}
}
Runtime Polymorphism
Runtime Polymorphism in Java is also known as dynamic method dispatch. It occurs when a method call is
resolved at runtime, and it is achieved using method overriding.
Overriding Methods
When we create a subclass of a class, it inherits behavior of the original class.
The subclass can reuse this inherited behavior. However, often it wants to
modify some of the inherited behavior to add the specialized behavior into the
subclass. So we modify the behavior by redefining the inherited method in the
subclass from the superclass. This redefining is popularly known as method
overriding.
The method in the super class is called as the overridden method and the
method in the subclass is called as the overriding method.
Rules of overriding a method
1. The method must have same method name as the method in the superclass.
In addition the type and order of arguments must be same.
[Link] access modifiers in subclass must be less restrictive than the original
method in superclass. For eg, if the method in superclass has s proctected
access modifier, we can override it with the public access modifier .
Private-> default-> projected-> public
3. We cannot override a final method of superclass
4. The overriding method must have same return type as the overridden method.
class Human{
//Overridden method
public void eat()
{
[Link]("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
[Link]("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
[Link]();
}
}
SUPER KEYWORD
The super keyword is used to refer superclass object. The uses of
super class are
- to call superclass method from subclass. If both subclass and
superclass contains the same method. That is when the methods
are overriden.
- if subclass and superclass contains the same variable, then we
can access the superclass variable using super keyword.
1. To call the super class method from subclass and to access
superclass variable from subclass:
We know that when we have two same methods in superclass and
subclass, andand when we want to access the method using
object of subclass, it always executes subclass method. We
cannot access superclass method using object of subclass . To
resolve this issue, we can use super keyword as shown in the
example.
Class First
{
int a=111;
Void function1()
{
[Link](" Inside function1 of first class") ;
}
}
Class Second extends First{
Int a =100;
Void function1() {
[Link](" Inside function1 of second class");
[Link]("the value of subclass a="+a) ;
[Link](" The value of superclass a="+super.a) ;//calling superclass variable
}
Public static void main(String args[]) {
Second s =new Second () ;
s.function1() ;
//calling super class method
super. function1() ;
Output: inside function1 of second class
}
The value of subclass a 100
}
The value of superclass a =111
Inside function1 of First class
Abstract Classes and methods.
- the keyword abstract can be applied to methods and classes. When we
apply the abstract keyword to a method, it becomes an abstract method
which means a method without any implementation. It means there is no
body of method. Declaration of such method has only the method signature
followed by semicolon.
Eg: abstract void method() ;
abstract void test() ;
- the class that contains one or more abstract method should be declared
with abstract keyword. When class is declared with abstract keyword, we
cannot create an objcet for that class
Eg: abstract class Test{
int a, b, c;
abstract void method1();
abstract void method2() ;
Void method3() {
[Link]("hello") ;
}
}
What is the use of abstract class?
Lets say we have a class Animal that has a method sound() and the
subclasses(see inheritance) of it like Dog, Lion, Horse, Cat etc. Since
the animal sound differs from one animal to another, there is no
point to implement this method in parent class. This is because every
child class must override this method to give its own implementation
details, like Lion class will say “Roar” in this method and Dog class
will say “Woof”.
So when we kno w that all the animal child classes will and should
override this method, then there is no point to implement this
method in parent class. Thus, making this method abstract would be
the good choice as by making this method abstract we force all the
sub classes to implement this method( otherwise you will get
compilation error), also we need not to give any implementation to
this method in parent class.
//abstract parent class
abstract class Animal{
//abstract method
public abstract void sound();
}
Public class Lion extends Animal{
Public void sound() {
[Link]("roar") ;
}
}
//Dog class extends Animal class
public class Dog extends Animal{
public void sound(){
[Link]("Woof");
}
public static void main(String args[]){
Dog obj = new Dog();
Lion obj1=new Lion() ;
[Link]();
[Link]();
}
}
- any class that contains abstract methods must be declared
with abstract keyword in class declaration.
- abstract method implies that it's implementation lies in
the subclasses, but declaring abstract methods as private or
final prevents overriding and hence it should not declare
with private or final methods.
- every subclass of an abstract class must provide an
implementation for all the abstract methods..
INTERFACES IN JAVA
Definition:An interface is a programming construct which
contains only public abstract methods and public static final
variables.
An interface is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the
abstract methods of the interfaces.
The java programming language provides three important
programming constructs. That is class, abstract class and
interfaces.
••Class: is fully implemented structure. All methods will have
body.
•• Interface: fully unimplemented structure. None of the
methods will have body.
•• Abstract Class: partially implemented / unimplemented
structure. Some will have body and some will have no body.
• the class which implements the interface should provide the
body for all the abstract methods defined in interface.
• the interface cannot be instantiated. That is we cannot create
an object of interface. The interface has no life if it is not
implemented in other classes.
•An interface does not contain any cinstructors.
• All of the methods in an interface are abstract. .
• An interface cannot contain instance fields. The only fields that
can appear in an interface must be declared both static and final.
• An interface is not extended by a class, it is implemented by a
class.
• An interface can extend multiple interfaces.
Syntax of Interface
interface interface_name
{
public static variables;
public abstract methods() ;
} // here interface is a keyword and interface_ name is any
valid user defined name. All variables are public static variables
and pubclis abstract methods.
Interfaces have the following properties −
••An interface is implicitly abstract. You do not need to use the abstract keyword
while declaring an interface.
••Each method in an interface is also implicitly abstract, so the abstract keyword
not needed.
••Methods in an interface are implicitly public.
Eg:
/* File name : [Link] */
interface Animal { interface Animal {
public static final int age=10; static final int age=10;
public void eat(); void eat();
public void travel(); void travel();
} }
Implementing Interfaces
A class uses the implements keyword to implement an interface. The
implements keyword appears in the class declaration following the extends
portion of the declaration.
/* File name : [Link] */
public class MammalInt implements Animal {
public void eat() {
[Link]("Mammal eats");
}
public void travel() {
[Link]("Mammal travels");
}
public int noOfLegs() { Output
return 0; Mammal eats
} Mammal travels
public static void main(String args[]) {
MammalInt m = new MammalInt();
[Link]();
[Link]();
}
}
When implementation interfaces, there are several
rules −
••A class can implement more than one interface at a
time.
••A class can extend only one class, but implement
many interfaces.
••An interface can extend another interface, in a
similar way as a class can extend another class.
••The signature of the interface method and the same
return type or subtype should be maintained when
overriding the methods.
••An implementation class itself can be abstract and if
so, interface methods need not be implemented
To Access Interface Variables.
Eg: interface XYZ {
int a= 100;
int b=200;
public void functionX () ;
}
Class ABC implements XYZ{
int c=300;
public voif functionX () {
[Link](" a="+a) ;
[Link]("b="+b) ;
[Link]("c="+c) ;
// a=400; error final variables cannot be altered
public ststic void main(String args[]) {
ABC a1= new ABC() ;
[Link] () ;
}
}
Difference between Interface and Class
1) Supported Methods
Class: A class can have both an abstract as well as concrete methods.
Interfaces: Interface can have only abstract methods. Java 8 onwards, it can have default as
well as static methods.
2) Multiple Inheritance
Class: Multiple Inheritance is not supported.
Interfaces: Interface supports Multiple Inheritance.
3) Supported Variables
Classes: final, non-final, static and non-static variables supported.
Interfaces: Only static and final variables are permitted.
4) Implementation
Classes: A class can implement an interface.
Interfaces: Interface can not implement an interface, it can extend an interface.
5) Keyword
Class: A class is declared using class keyword.
Interfaces: Interface is declared using interface keyword.
6) Inheritance
Class: A class can inherit another class using extends keyword and implement an interface.
Interfaces: Interface can inherit only an inteface.
7) Inheritance
Classes: A class can be inherited using extends keyword.
Interfaces: Interface can only be implemented using implements keyword.
8) Access
Classes: A class can have any type of members like private, public.
Interfaces: Interface can only have public members.
9) Constructor
Classes: A class can have constructor methods.
Interface: Interface can not have a constructor
Access Control Modifers(visibility Control)(visibility modifiers)
The access modifiers in Java specifies the accessibility or scope of a field,
method, constructor, or class. We can change the access level of fields,
constructors, methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
Protected: The access level of a protected modifier is within the package
and outside the package through child class. If you do not make the child
class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.
1) Private
The private access modifier is accessible only within the class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class
contains private data member and private method. We are accessing
these private members from outside the class, so there is a compile-
time error.
class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}
}
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
//save by [Link]
package pack;
class A{
void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
It provides more accessibility than the default modifer.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.
//save by [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
Example of public access modifier
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello
Packages in Java
Package in Java is a mechanism to encapsulate a group of
classes, sub packages and interfaces.
Purpose of using packages:
- first, it provides a mechanism by which related pieces of a
program can be organized as a unit. Classes defined within a
package must be accessed through their package name. This a
package provides a way to name a collection of classes
- secondly, a package handles java access control mechanism.
Classes defined within a package can be made private to that
package and not accessible by code outside the package. Thus,
the package provides a means by which classes can be
encapsulated.
Packages are classified into two categories
1. Java API packages
2. User defined packages
Java API packages
The java provides thousands of built in classes and remembering
each class name is very difficult. The java organized the collection
of classes into packages based on the functionality. We can easily
remember the package name instead of class name.
Predefined packages
Java provides various predefined classes and interfaces (API’s)
organized under packages. These are known as predefined
packages, following is the list of predefined packages in java −
[Link] − This package provides the language basics.
[Link] − This packages provides classes and interfaces (API’s)
related to collection frame work, events, data structure and other
utility classes such as date.
[Link] − This packages provides classes and interfaces for file
operations, and other input and output operation
[Link] − This packages provides classes and interfaces related to
networking.
[Link] − This packages provides classes and interfaces for
accessing/manipulating the data stored in databases and data sources.
[Link] − This packages provides classes and interfaces to create GUI
components in Java.
Eg: import [Link];
class Student2{ }
2)defining User defined Packages
All the classes in java belong to some package. When no package
statement is specified, the default package is used. The default package
has no name, which makes the default package transparent . While
default package is fine for small and simple programs, it's not good for
real applications. Most of the time, we will define one or more packages
for our code.
• to create a package, put a package keyword at the top of a java. The
classes declared within that file will then belong to the specified package.
.
Syntax: package packagename;
Eg: package pack1;
Class A{}
• java uses the file system to manage packages, with
each package stored in its own directory. The classes
created under this package will be stored under pack1
directory.
Creating User Defined Packages
Step1: let us create a program which is part of package
called pack1.
Package pack1;
Public class packageexample{
public void packagemethod() {
[Link](" I am method from pack1 package
example") ;
}
}
Step2: place this [Link] file in C:\ directory
and compile the program as shown below we have to use -d
option to create the pack1 directory automatically.
The command is javac -[Link] <---
After typing this command press enter button, we can see the
directory pack1 and under this package ,
[Link] file will be created.
Step3: Create another file called [Link] in pack2
package as shown below.
Package pack2;
Import pack1. *;
Puclic class packagedemo{
public static void main(String args[]) {
Packageexample obj=new packageexample () ;
[Link]() ;
}
}
In this file we are trying to import the pack1 classes and
creating an object of packageexample class and call to
packmethod().
Step4: place this file also in C:\ and compile the program
using -d option as shown below.
C:\ javac -[Link]
It creates pack2 directory and class file is also copied to that
directory automatically.
Step5: the compilation of both the classes are completed.
Now, let us execute the [Link]
C:\ java [Link]
I am method from packageexample
Java IO : Input-output in Java
Java brings various Streams with its I/O package that helps the
user to perform all the input-output operations. These streams
support all the types of objects, data-types, characters, files
etc. to fully execute the I/O operations.
Before exploring various input and output streams
let's look at 3 standard or default streams that Java
has to provide which are also most common in use:
[Link]
This is the standard input stream([Link]) that is
used to read characters from the keyboard or any
other standard input device.
[Link]
This is the standard output stream([Link]) that
is used to produce the result of a program on an
output device like the computer screen.
[Link]("GfG! ");
[Link]("GfG! ");
[Link]("Printing simple integer: x =
%d%n", x);
[Link]
It will display error msg using println method
[Link]("Error code: %d, Message: %s%n",
404, "Not Found");
Types of Streams
Depending on the type of operations, streams can be
divided into two primary classes:
Input Stream: These streams are used to read data that
must be taken as an input from a source array or file or
any peripheral device. For eg., FileInputStream,
BufferedInputStream, ByteArrayInputStream etc.
Output Stream: These streams are used to write data
as outputs into an array or file or any output
peripheral device. For eg., FileOutputStream,
BufferedOutputStream, ByteArrayOutputStream etc.
Depending on the types of file, Streams can be
divided into two primary classes which can be
further divided into other classes as can be seen
through the diagram below followed by the
explanations.
ByteStream
This is used to process data byte by byte (8 bits).
Though it has many classes, the FileInputStream
and the FileOutputStream are the most popular
ones. The FileInputStream is used to read from the
source and FileOutputStream is used to write to the
destination. Here is the list of various ByteStream
Classes:
Stream class Description
BufferedInputStream- It is used for Buffered Input Stream.
DataInputStream- It contains method for reading java
standard datatypes.
FileInputStream - This is used to reads from a file
InputStream - This is an abstract class that describes
stream input.
PrintStream- This contains the most used print() and
println() method
BufferedOutputStream- This is used for Buffered Output
Stream.
DataOutputStream - This contains method for writing java
standard data types.
FileOutputStream- This is used to write to a file.
OutputStream- This is an abstract class that describe stream
CharacterStream
In Java, characters are stored using Unicode
conventions (Refer this for details). Character stream
automatically allows us to read/write data character
by character. Though it has many classes, the
FileReader and the FileWriter are the most popular
ones. FileReader and FileWriter are character streams
used to read from the source and write to the
destination respectively. Here is the list of various
CharacterStream Classes
Stream class Description
BufferedReader- It is used to handle buffered input stream.
FileReader This is an input stream that reads from file.
InputStrea-mReaderThis input stream is used to translate byte
to character.
OutputStreamReader This output stream is used to
translate character to byte.
Reader This is an abstract class that define character
stream input.
PrintWriter This contains the most used print() and println()
method
Writer This is an abstract class that define character stream
output.
BufferedWriter This is used to handle buffered output
stream.
FileWriter This is used to output stream that writes to file.