0% found this document useful (0 votes)
20 views46 pages

Module 2

Uploaded by

amogh.patadi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views46 pages

Module 2

Uploaded by

amogh.patadi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

MODULE-2

I/O Basics &Files


Module Contents:
Inheritance: Packages and Interfaces:
Basics, Defining a package,
Using super, Finding packages and CLASSPATH,
Creating multilevel hierarchy, A short package example,
When constructors are called, Access protection,
Method Overriding, Importing packages,
Applying method overriding, Defining an interface,
Using abstract classes, Implementing interfaces,
Using final with inheritance, Nested interfaces,
The object class. Applying interfaces,
Variables in interfaces.
Inheritance Basics:
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).
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
Inheritance is used
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Terms used in Inheritance
• Class: A class is a group of objects which have common properties. It is a template
or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when you
create a new class. You can use the same fields and methods already defined in
the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a
new class that derives from an existing class.
The meaning of "extends" is to in.
crease the functionality

The relationship between the two classes is


Programmer IS-A Employee.
It means that Programmer is a type of Employee.
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
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
When one class inherits multiple classes, it is known as multiple inheritance.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");} Output:
}
class TestInheritance{ Barking….
public static void main(String args[]){ Eating…..
Dog d=new Dog();
d.bark();
d.eat();
} }
Multilevel Inheritance
In Multi-Level Inheritance in Java, a class extends to another class that is already
extended from another class.
For example, if there is a class A that extends class B and class B extends from another
class C, then this scenario is known to follow Multi-level Inheritance.

Consider three classes, class Vehicle, class Car, and class SUV. Here, the class Vehicle is
the grandfather class. The class Car extends class Vehicle and the class SUV extends class
Car.

Consider three classes – Car, Maruti and Maruti800. We have done a setup – class Maruti
extends Car and class Maruti800 extends Maruti. With the help of this Multilevel hierarchy
setup our Maruti800 class is able to use the methods of both the classes (Car and Maruti).

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat(); } }
Hierarchical Inheritance
When two or more classes are inherited from a single class, it is known as hierarchical
inheritance
class Animal{ class TestInheritance3{
void eat(){System.out.println("eating...");} public static void main(String args[]){
} Cat c=new Cat();
class Dog extends Animal{ c.meow();
void bark(){System.out.println("barking...");} c.eat();
//c.bark();//C.T.Error
}
}
class Cat extends Animal{ }
void meow(){System.out.println("meowing...");} Output:
}
meowing...
eating...
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there will
be compile time error.
Using Super
Used to
1.Access the members of the superclass from within the subclass:
2.Invoke the superclass constructor from within the subclass constructor.
3.Resolve ambiguity between a field or method in the subclass and a field or method in the
superclass.
4.Access the static members of the superclass from within the subclass.

// Parent class
class School
{
// Instance variables
int id;
String name = "SSM Public School";
}
class Teacher extends School
{
// Instance variable in the child class
int id;
String name;
void printSchoolName() {
// Using super.name, we can access the name variable of the parent class
// Using this.name, we can access the name variable of the child class
System.out.println("School Name: " + super.name);
}
public static void main(String[] args) {
Teacher ob = new Teacher();
ob.printSchoolName();
}
}
When constructors are called,
Constructor is a block of code that initializes the newly created object.
A constructor resembles an instance method in java but it’s not a method as it doesn’t have a
return type.
In short constructor and method are different.
People often refer constructor as special type of method in Java.
Constructor has same name as the class and looks like this in a java code.
There are two types of constructors in Java:
1.Default constructor (no-arg constructor)
2.Parameterized constructor
Syntax:
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1(); } } Bike is created
Example:
/Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id; public static void main(String args[]){
String name; //creating objects and passing values
//creating a parameterized constructor Student4 s1 = new Student4(111,"Karan");
Student4(int i,String n){ Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
id = i;
s1.display();
name = n; s2.display();
} }
//method to display the values }
void display()
{
System.out.println(id+" "+name);
}
Constructor Overloading in Java
Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists.
They are differentiated by the compiler by the number of parameters in the list and their types.
//Java program to overload constructors
class Student5{ void display()
int id; {
String name; System.out.println(id+" "+name+" "+age);
int age; }
//creating two arg constructor
Student5(int i,String n){ public static void main(String args[]){
id = i; Student5 s1 = new Student5(111,"Karan");
name = n; Student5 s2 = new Student5(222,"Aryan",25);
} s1.display();
Student5(int i,String n,int a){ s2.display();
}
id = i; name = n; age=a; }
}
Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
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

//Creating a parent class


class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[])
{ //creating an instance of child class Bike obj = new Bike(); obj.run(); } }
Applying method overriding
//Java Program to demonstrate the real scenario of Java Method Overriding
//where three classes are overriding the method of a parent class.
//Creating a parent class. class AXIS extends Bank
class Bank{ { int getRateOfInterest(){return 9; } }
int getRateOfInterest(){return 0;} //Test class to create objects and call the methods
class Test2{
}
public static void main(String args[]){
//Creating child classes. SBI s=new SBI();
class SBI extends Bank{ ICICI i=new ICICI();
int getRateOfInterest(){return 8;} AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest())
}
;
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest(
class ICICI extends Bank{ ));
int getRateOfInterest(){return 7;} System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest(
)); } }
}
Using abstract classes
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).
Abstraction lets you focus on what the object does instead of how it does it.

There are two ways to achieve abstraction in java


1. Abstract class (0 to 100%)
2. Interface (100%)

Points to remember for ABSTRACT CLASS


• 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.
abstract class A{} ======abstract class
abstract void printStatus();//no method body and abstract ======abstract method
Example:
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike
{
void run(){System.out.println("running safely");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In real scenario, object is provided through method, e.g., getShape()
method
s.draw(); } }
Using final with inheritance
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be used with :
1.variable

2.method

3.class
If you make any variable as final, you cannot change the value
of final variable(It will be constant).
Eg: class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run(); } }
If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
} } Output: Compile Time Error
If you make any class as final, you cannot extend it.
final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Importing packages
Defining an interface,
Implementing interfaces,
Nested interfaces,
Applying interfaces,
Variables in interfaces.
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.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.
There are mainly three reasons to use interface. They are given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality
of multiple inheritance.
• It can be used to achieve loose coupling.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
The relationship between classes and interfaces
As shown in the figure given below,
a class extends another class,
an interface extends another interface, but interface printable
a class implements an interface. {
void print();
}
class A6 implements printable{
public void print()
{System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//
In real scenario, object is provided by method e.g. getDrawable() d.draw();
} }
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.
interface Printable{
void print();
} • multiple inheritance is not
interface Showable{ supported in the case of
void show();
class because of ambiguity.
}
class A7 implements Printable,Showable{ • However, it is supported in
public void print(){System.out.println("Hello");} case of an interface because
public void show(){System.out.println("Welcome");}
there is no ambiguity.

public static void main(String args[]){ • It is because its


A7 obj = new A7(); implementation is provided
obj.print();
by the implementation class.
obj.show();
}
}
The object class
The Object class is the parent class of all the classes in java by default. In other words, it
is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know.
Say that parent class reference variable can refer the child class object, know as upcasting.
The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

Example, there is getObject() method that returns an object but it can be of any type like
Employee,Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();//we don't know what object will be returned

The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
Cloning
The object cloning is a way to create exact copy of an object.
The clone() method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object
clone we want to create.
If we don't implement Cloneable interface, clone() method
generates CloneNotSupportedException.
The clone() method is defined in the Object class.
Syntax of the clone() method is as follows:
protected Object clone() throws CloneNotSupportedException
class Student18 implements Cloneable{ Student18 s2=(Student18)s1.clone();
int rollno; System.out.println(s1.rollno+" "+s1.name);
String name; System.out.println(s2.rollno+" "+s2.name);
Student18(int rollno,String name) }
{ catch(CloneNotSupportedException c)
{
this.rollno=rollno;
}
this.name=name; }
} }
public Object clone()throws CloneNotSupportedException
{
return super.clone(); Output:
101 amit
}
101 amit
public static void main(String args[]){
try
{ Student18 s1=new Student18(101,"amit");
Packages .

Defining a package
 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.

Advantage of Java Package


1) Java package is used to categorize classes and
interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision
The package keyword is used to create a package in java.
package mypack;
public class Simple
{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
Syntax: javac -d directory javafilename
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 d:/abc (in case of windows).
If you want to keep the package within the same directory, you can use . (dot).
Finding packages and CLASSPATH,
Java packages are mirrored by directories.
Java run-time system looks for packages from three parts.
Current folder
First, the Java run-time system uses the current working directory as its
starting point.
If your package is in a subdirectory of the current directory, it will be found.
CLASSPATH
Second, you can specify a directory path or paths by setting
the CLASSPATH environmental variable.
-classpath
Third, you can use the -classpath option with java and javac to specify the
path to your classes.
package example
// A simple package
package MyPack;
class MyClass
{
void me()
{ System.out.println("hi from package"); }
}
class Main
{ public static void main(String args[])
{
MyClass c = new MyClass();
c.me();
}
}
In order for a program to find MyPack, one of three things must be true.
Either the program can be executed from a directory immediately
above MyPack, or the CLASSPATH must be set to include the path to MyPack,
or the -classpath option must specify the path to MyPack when the program is
run via java.
When the second two options are used, the class path must not include MyPack,
itself.
It must simply specify the path to MyPack.
For example, in a Windows environment, if the path to MyPack is
C:\MyPrograms\Java\MyPack

then the class path to MyPack is


C:\MyPrograms\Java
Access protection
In java, the access modifiers define the accessibility of the class and its members.
Java has four access modifiers, and they are default, private, protected, and public.
The package is a container of classes, sub-classes, interfaces, and sub-packages.
The class acts as a container of data and methods.
So, the access modifier decides the accessibility of class members across the

different packages.
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.
Nested Interfaces
An interface declared within another interface or class, is known as a nested interface.
The nested interfaces are used to group related interfaces so that they can be easy to maintain.
The nested interface must be referred to by the outer interface or class.
It can't be accessed directly.
interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message
{ public void msg() { System.out.println("Hello nested interface"); }
public static void main(String args[])
{
Showable.Message message=new TestNestedInterface1();//upcasting here
message.msg();
} }
Variables in interface
In Java, an interface variable is implicitly public, static, and final.
This means that the variable's value cannot be changed once it is assigned.
Furthermore, interface variables are accessible to all implementing classes,
promoting code reusability and standardization.
public interface Constants {
String DATABASE_URL = "jdbc:mysql://localhost:3306/mydatabase";
String USERNAME = "root";
String PASSWORD = "password123";
}
public class DatabaseConnection {
// Code for establishing a database connection using the constants
}
public interface Currency { public class Main
String SYMBOL = "$"; {
double convertToUSD(double amount);
public static void main(String[] args)
}
public class Dollar implements Currency { {
public double convertToUSD(double amount) { Currency dollar = new Dollar();
return amount; Currency euro = new Euro();
}
}
double amount = 100;
public class Euro implements Currency {
public double convertToUSD(double amount) { System.out.println("Amount in dollars: " +
return amount * 1.18;
} dollar.convertToUSD(amount) + SYMBOL);
}
System.out.println("Amount in euros: " +

euro.convertToUSD(amount) + SYMBOL);
}

You might also like