Java Unit-2
Java Unit-2
CSE II-I
BY
Dr.N.Lingareddy
Associate professor
UNIT-II
Java Inheritance Basics
Inheritance Concept
The inheritance is a very useful and powerful concept of object-oriented programming. In java, using the
inheritance concept, we can use the existing features of one class in another class. The inheritance
provides a greate advantage called code re-usability. With the help of code re-usability, the commonly
used code in an application need not be written again and again.
The inheritance can be defined as follows.
The inheritance is the process of acquiring the properties of one class to another class.
Inheritance Basics
In inheritance, we use the terms like parent class, child class, base class, derived class, superclass, and
subclass.
The Parent class is the class which provides features to another class. The parent class is also known
as Base class or Superclass.
The Child class is the class which receives features from another class. The child class is also known
as the Derived Class or Subclass.
In the inheritance, the child class acquires the features from its parent class. But the parent class never
acquires the features from its child class.
The java programming language does not support multiple inheritance type. However, it
provides an alternate with the concept of interfaces.
Syntax
class <ChildClassName> extends <ParentClassName>{
...
//Implementation of child class
...
}
In a java programming language, a class extends only one class. Extending multiple
classes is not allowed in java.
Let's look at individual inheritance types and how they get implemented in java with an
example.
Example
class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Value of a is " + a);
}
}
public class SingleInheritance {
Example
class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Value of a is " + a);
}
}
class ChildChildClass extends ChildClass{
void display() {
System.out.println("Inside ChildChildClass!");
}
}
public class MultipleInheritance {
}
Hierarchical Inheritance in java
In this type of inheritance, two or more child classes derive from one parent class. Look
at the following example java code.
Example
class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Inside ChildClass!");
System.out.println("Value of a is " + a);
}
}
class ChildClassToo extends ParentClass{
void display() {
System.out.println("Inside ChildClassToo!");
System.out.println("Value of a is " + a);
}
}
public class HierarchicalInheritance {
Example
class ParentClass{
int a;
ParentClass(){
System.out.println("Inside ParentClass constructor!");
}
}
class ChildClass extends ParentClass{
ChildClass(){
System.out.println("Inside ChildClass constructor!!");
}
}
class ChildChildClass extends ChildClass{
ChildChildClass(){
System.out.println("Inside ChildChildClass constructor!!");
}
}
public class ConstructorInInheritance {
In java, we can not employ all access specifiers on everything. The following table describes where we
can apply the access specifiers.
Let's look at the following example java code, which generates an error because a class does not allow
private access specifier unless it is an inner class.
Example
private class Sample{
...
}
In java, the accessibility of the members of a class or interface depends on its access specifiers. The
following table provides information about the visibility of both data members and methods.
The public members can be accessed everywhere.
🔔 The private members can be accessed only inside the same class.
🔔 The protected members are accessible to every child class (same package or other
packages).
🔔 The default members are accessible within the same package but not outside the
package.
Example
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample {
Specialization
Specification
Construction
Eextension
Limitation
Combination
Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent class. It holds the
principle of substitutability.
Specification
This is another commonly used form of inheritance. In this form of inheritance, the parent class just
specifies which methods should be available to the child class but doesn't implement them. The java
provides concepts like abstract and interfaces to support this form of inheritance. It holds the principle of
substitutability.
Construction
This is another form of inheritance where the child class may change the behavior defined by the parent
class (overriding). It does not hold the principle of substitutability.
Eextension
This is another form of inheritance where the child class may add its new properties. It holds the
principle of substitutability.
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It does not hold
the principle of substitutability.
Combination
This is another form of inheritance where the subclass inherits properties from multiple parent classes.
Java does not support multiple inheritance type.
Costs of Inheritance
Inheritance decreases the execution speed due to the increased time and effort it takes, the
program to jump through all the levels of overloaded classes.
Inheritance makes the two classes (base and inherited class) get tightly coupled. This means
one cannot be used independently of each other.
The changes made in the parent class will affect the behavior of child class too.
The overuse of inheritance makes the program more complex.
Example
class ParentClass{
void showData() {
System.out.println("Inside the ChildClass");
System.out.println("ChildClass num = " + num);
System.out.println("ParentClass num = " + super.num);
}
}
obj.showData();
Example
class ParentClass{
int num1 = 10;
void showData() {
System.out.println("\nInside the ParentClass showData method");
System.out.println("ChildClass num = " + num1);
}
}
void showData() {
System.out.println("\nInside the ChildClass showData method");
System.out.println("ChildClass num = " + num2);
super.showData();
}
}
obj.showData();
//super.showData(); // super can't be used here
}
}
super to call parent class constructor
When an object of child class is created, it automatically calls the parent class default-
constructor before it's own. But, the parameterized constructor of parent class must be
called explicitly using the super keyword inside the child class constructor.
Let's look at the following example java code.
Example
class ParentClass{
int num1;
ParentClass(){
System.out.println("\nInside the ParentClass default constructor");
num1 = 10;
}
ParentClass(int value){
System.out.println("\nInside the ParentClass parameterized
constructor");
num1 = value;
}
}
int num2;
ChildClass(){
super(100);
System.out.println("\nInside the ChildClass constructor");
num2 = 200;
}
}
}
}
Example
}
final with methods
When a method defined with the final keyword, it does not allow it to override. The final
method extends to the child class, but the child class can not override or re-define it. It
must be used as it has implemented in the parent class.
Let's look at the following example java code.
Example
class ParentClass{
void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}
Example
void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
}
Java Pylymorphism
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
If you overload a static method in Java, it is the example of compile time polymorphism. Here, we
will focus on runtime polymorphism in java.
In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For
example:
1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting
For upcasting, we can use the reference variable of class type or an interface type. For
Example:
1. interface I{}
2. class A{}
3. class B extends A implements I{}
In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and
overrides its run() method. We are calling the run method by the reference variable of Parent class. Since
it refers to the subclass object and subclass method overrides the Parent class method, the subclass
method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splendor();//upcasting
9. b.run();
10. }
11. }
drawing rectangle...
drawing circle...
drawing triangle...
Example
class ParentClass{
void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}
}
}
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the
Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Java Interface Example: Drawable
In this example, the Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used by someone else.
The implementation part is hidden by the user who uses the interface.
File: TestInterface1.java
Example
interface ParentInterface{
void parentMethod();
}
obj.childMethod();
obj.parentMethod();
}
Nested Interface in Java
Note: An interface can have another interface which is known as a nested interface. We
will learn it in detail in the nested classes chapter. For example:
1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }
Syntax
abstract class <ClassName>{
...
}
Example
import java.util.*;
}
class Rectangle extends Shape {
void printArea() {
System.out.println("*** Finding the Area of Rectangle ***");
System.out.print("Enter length and breadth: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Rectangle is: " + length * breadth);
}
}
An abstract class can not be instantiated but can be referenced. That means we can not create an
object of an abstract class, but base reference can be created.
In the above example program, the child class objects are created to invoke the overridden abstract
method. But we may also create base class reference and assign it with child class instance to invoke
the same. The main method of the above program can be written as follows that produce the same
output.
Example
public static void main(String[] args) {
Shape obj = new Rectangle(); //Base class reference to Child class instance
obj.printArea();
Return
Method Description Value
hashCode() returns the hashcode number for object being used. int
notifyAll() wakes up all the threads, waiting on invoking object's monitor. void
wait() causes the current thread to wait, until another thread notifies. void
wait(long,int) causes the current thread to wait for the specified milliseconds and void
nanoseconds, until another thread notifies.
JAVA - PACKAGES:
What is package:
Packages are used in Java, in-order to avoid name conflicts and to control access of class,
interface and enumeration etc. A package can be defined as a group of similar types of
classes, interface, enumeration or sub-package.
Using package it becomes easier to locate the related classes and it also
provides a good structure for projects with hundreds of classes and other files.
package mypackage;
public class student
{
Statement;
}
The above statement will create a package name mypackage in the project directory.
Java uses file system directories to store packages. For example the .java file for any class
you define to be part of mypackage package must be stored in
A package is always defined as a separate folder having the same name as the
package name.
Store all the classes in that package folder.
All classes of the package which we wish to access outside the package must be
declared public.
All classes within the package must have the package statement as its first line.
All classes of the package must be compiled before use (So that they are error
free)
Example of Java packages:
Package mypack;
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
For example
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).
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.
}
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.
{
public void msg()
{
System.out.println("Hello java");}
}
//save by
B.java
package
mypack;
import pack.*;
class B
{
public static void main(String args[])
}
}
{
A obj = new
A();
obj.msg();
}
}
Output: Hello java
2) Using packagename.classname:
If you import package.classname then only declared class of this package will be
accessible.
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");}
}
}
//save by
B.java
package
mypack;
import
pack.A;
class B
{
public static void main(String args[])
}
}
{
A obj = new
A();
obj.msg();
}
}
Output: Hello
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
{
public void msg()
{
System.out.println("Hello");}
}
}
//save by
B.java
package
mypack; class
B
{
public static void main(String args[])
}
}
{
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
Output: Hello
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.
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.
package com.javatpoint.core;
class Simple{
}
}
To Compile: javac -d . Simple.java
}
}
For example:
//save as
Simple.java
package mypack;
public class
Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
To Compile:
Simple.java To Run:
To run this program from e:\source directory, you need to set classpath of the directory
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:
Java.io package
Stream in java
In java, the IO operations are performed using the concept of streams. Generally, a
stream means a continuous flow of data. In java, a stream is a logical container of
data that allows us to read from and write to it. A stream can be linked to a data
source, or data destination, like a console, file or network connection by java IO
system. The stream-based IO operations are faster than normal IO operations.
The Stream is defined in the java.io package.
To understand the functionality of java streams, look at the following picture.
}
}
In java, the stream-based IO operations are performed using two separate streams
input stream and output stream. The input stream is used for input operations, and
the output stream is used for output operations. The java stream is composed of
bytes.
In Java, every program creates 3 streams automatically, and these streams are
attached to the console.
The Java streams support many different kinds of data, including simple bytes,
primitive data types, localized characters, and objects.
Java provides two types of streams, and they are as follows.
Byte Stream
Character Stream
The following picture shows how streams are categorized, and various built-in
classes used by the java IO system.
}
}
Both character and byte streams essentially provides a convenient and efficient way
to handle data streams in Java.
In the next tutorial, we will explore different types of streams in java.
InputStream class
The InputStream class has defined as an abstract class, and it has the following
methods which have implemented by its concrete classes.
1 int available()
It returns the number of bytes that can be read from the input stream.
2 int read()
It reads the next byte from the input stream.
3 int read(byte[] b)
}
}
It reads a chunk of bytes from the input stream and store them in its byte array, b.
4 void close()
It closes the input stream and also frees any resources connected with this input stream
OutputStream class
The OutputStream class has defined as an abstract class, and it has the following
methods which have implemented by its concrete classes.
1 void write(int n)
2 void write(byte[] b)
3 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void close()
It closes the output stream and also frees any resources connected with this output strea
try {
System.out.print("Enter any character: ");
char c = (char)read.read();
System.out.println("You have entered '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
read.close();
}
}
o/p
}
}
out.write(data.getBytes());
System.out.println("Writing data into a file is success!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
}
}
}
}
}
o/p
The java character stream is defined by two abstract classes, Reader and Writer.
The Reader class used for character stream based input operations, and the Writer
class used for charater stream based output operations.
The Reader and Writer classes have several concreate classes to perform various
IO operations based on the character stream.
}
}
The following picture shows the classes used for character stream operations.
Reader class
The Reader class has defined as an abstract class, and it has the following methods
which have implemented by its concrete classes.
S.No
. Method with Description
1 int read()
S.No
. Method with Description
5 String readLine()
It reads a line of text. A line is considered to be terminated by any oneof a line feed ('\n
return ('\r'), or a carriage returnfollowed immediately by a linefeed.
6 boolean ready()
It tells whether the stream is ready to be read.
7 void close()
It closes the input stream and also frees any resources connected with this input stream.
Writer class
The Writer class has defined as an abstract class, and it has the following methods
which have implemented by its concrete classes.
1 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void write(int c)
It writes a string.
7 Writer append(char c)
10 void close()
It closes the output stream and also frees any resources connected with this output strea
name = in.readLine();
o/p
}
}
try {
out.write(msg);
System.out.println("Writing done!!!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
}
}
}
o/p