0% found this document useful (0 votes)
4 views60 pages

java Unit 2

Uploaded by

sowmyaprema249
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
4 views60 pages

java Unit 2

Uploaded by

sowmyaprema249
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 60

Method

What is a method in Java?

 A method is a block of code or collection of statements or a set of code


grouped together to perform a certain task or operation.
 It is used to achieve the reusability of code.
 We write a method once and use it many times. We do not require to
write code again and again.
 It also provides the easy modification and readability of code, just by
adding or removing a chunk of code.
 The method is executed only when we call or invoke it.

Method Declaration

 The method declaration provides information about method attributes,


such as visibility, return-type, name, and arguments.
 It has six components that are known as method header, as we have
shown in the following figure.

Method Signature:

1
Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.

Access Specifier:

Access specifier or modifier is the access type of the method. It specifies


the visibility of the method. Java provides four types of access specifier. They
are

o Public: The method is accessible by all classes when we use public


specifier in our application.
o Private: When we use a private access specifier, the method is accessible
only in the classes in which it is defined.
o Protected: When we use protected access specifier, the method is
accessible within the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method
declaration, Java uses default access specifier by default. It is visible only
from the same package only.

Return Type:

 Return type is a data type that the method returns. It may have a primitive
data type, object, collection, void, etc.
 If the method does not return anything, we use void keyword.

Method Name:

 It is a unique name that is used to define the name of a method.


 It must be corresponding to the functionality of the method.
 Suppose, if we are creating a method for subtraction of two numbers, the
method name must be subtraction().
 A method is invoked by its name.

Parameter List:

 It is the list of parameters separated by a comma and enclosed in the


pair of parentheses.

 It contains the data type and variable name.

2
 If the method has no parameter, left the parentheses blank.

Method Body:

 It is a part of the method declaration. It contains all the actions to be


performed. It is enclosed within the pair of curly braces.

Types of Method

There are two types of methods in Java:

o Predefined Method
o User-defined Method

Predefined Method

 In Java, predefined methods are the method that is already defined in the
Java class libraries is known as predefined methods.

 It is also known as the standard library method or built-in method. We


can directly use these methods just by calling them in the program at any
point.

 Some pre-defined methods are length(), equals(), compareTo(),


sqrt(), etc.

 When we call any of the predefined methods in our program, a series of


codes related to the corresponding method runs in the background that is
already stored in the library.

 Each and every predefined method is defined inside a class.

 Such as print() method is defined in the java.io.PrintStream class.

 It prints the statement that we write inside the method. For


example, print("Java"), it prints Java on the console.

Example

public class Demo


{
3
public static void main(String[] args)
{
System.out.println("The maximum number is: " + Math.max(9,7));
}
}

In the above example, we have used three predefined methods main(),


print(), and max(). We have used these methods directly without declaration
because they are predefined. The print() method is a method
of PrintStream class that prints the result on the console. The max() method is
a method of the Math class that returns the greater of two numbers.

User-defined Method

 The method written by the user or programmer is known as a user-


defined method.

Example:1

import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
int num=scan.nextInt();
findEvenOdd(num);
}
public static void findEvenOdd(int num)
{
if(num%2==0)
System.out.println(num+" is even");
4
else
System.out.println(num+" is odd");
}
}

Output 1:

Enter the number: 12


12 is even

Output 2:

Enter the number: 99


99 is odd

Example:2

public class Addition


{
public static void main(String[] args)
{
int a = 19;
int b = 5;
int c = add(a, b); //a and b are actual parameters
System.out.println("The sum of a and b is= " + c);
}
public static int add(int n1, int n2) //n1 and n2 are formal parameters
{
int s;
s=n1+n2;
return s; //returning the sum
}
}

5
Static Method

 A method that has static keyword is known as static method.


 A method that belongs to a class rather than an instance of a class is
known as a static method.
 We can also create a static method by using the keyword static before the
method name.

Advantages of static method

 The main advantage of a static method is that we can call it without


creating an object.
 It can access static data members and also change the value of it. It is
used to create an instance method.
 It is invoked by using the class name. The best example of a static
method is the main() method.

Example:

public class Display


{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static method.");
}
}

6
Instance Method

 The method of the class is known as an instance method.

 It is a non-static method defined in the class.

 Before calling or invoking the instance method, it is necessary to create


an object of its class. Let's see an example of an instance method.

Example:

public class InstanceMethodExample


{
public static void main(String [] args)
{
InstanceMethodExample obj = new InstanceMethodExample();
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
public int add(int a, int b)
{
s = a+b;
return s;
}
}

There are two types of instance method:

o Accessor Method
o Mutator Method

Accessor Method:
 The method(s) that reads the instance variable(s) is known as the accessor
method.

7
 We can easily identify it because the method is prefixed with the
word get. It is also known as getters.
 It returns the value of the private field. It is used to get the value of the
private field.

Example

public int getId()


{
return Id;
}
Mutator Method:
 The method(s) read the instance variable(s) and also modify the values.
 We can easily identify it because the method is prefixed with the
word set. It is also known as setters or modifiers. It does not return
anything.
 It accepts a parameter of the same data type that depends on the field.
 It is used to set the value of the private field.

Example

public void setRoll(int roll)


{
this.roll = roll;
}

Example of accessor and mutator method

public class Student


{
private int roll;
private String name;
public int getRoll()
{
return roll;
}
public void setRoll(int roll)
{

8
this.roll = roll;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public void display()
{
System.out.println("Roll no.: "+roll);
System.out.println("Student name: "+name);
}
}

Abstract Method

 The method that does not has method body is known as abstract method.

 In other words, without an implementation is known as abstract method.

 It always declares in the abstract class. It means the class itself must be
abstract if it has abstract method.

 To create an abstract method, we use the keyword abstract.

Syntax
abstract void method_name();

Example
abstract class Demo
{
abstract void display();
}
public class MyClass extends Demo
{

9
void display()
{
System.out.println("Abstract method?");
}
public static void main(String args[])
{
Demo obj = new MyClass();
obj.display();
}
}

Method Overloading

 If a class has multiple methods having same name but different in


parameters, it is known as Method Overloading.

 If we have to perform only one operation, having same name of the


methods increases the readability of the program.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

1) Method Overloading: changing no. of arguments


In this example, we have created two methods, first add() method performs
addition of two numbers and second add method performs addition of three
numbers.

10
Example:

In this example, we are creating static methods so that we don't need to create
instance for calling methods.

class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type.

The first add method receives two integer arguments and second add method
receives two double arguments.

Example:

class Adder
{
static int add(int a, int b)

11
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}

Can we overload java main() method?

Yes, by method overloading. We can have any number of main methods


in a class by method overloading. But JVM calls main() method which receives
string array as arguments only.

Example:

class TestOverloading4
{
public static void main(String[] args)
{
System.out.println("main with String[]");
}
public static void main(String args)
{
System.out.println("main with String");

12
}
public static void main()
{
System.out.println("main without args");
}
}

Inner and Nested Classes


The class written within is called the nested class, and the class that holds the
inner class is called the outer class.

Syntax
class Outer_Demo
{
class Inner_Demo

}
}
Nested classes are divided into two types −
 Non-static nested classes − These are the non-static members of a class.
 Static nested classes − These are the static members of a class.

13
Inner Class
Creating an inner class is quite simple. You just need to write a class
within a class. Unlike a class, an inner class can be private and once you declare
an inner class private, it cannot be accessed from an object outside the class.

Example:
class Outer_Demo
{
int num;
private class Inner_Demo
{
public void print()
{
System.out.println("This is an inner class");
}
}

void display_Inner()
{
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}

public class My_class


{

14
public static void main(String args[])
{
Outer_Demo outer = new Outer_Demo();

outer.display_Inner();
}
}

Output
This is an inner class.

STATIC MEMBERS

 In Java, static members are those which belongs to the class and you can
access these members without instantiating the class.

 The static keyword can be used with methods, fields, classes


(inner/nested), blocks.

Static Methods

You can create a static method by using the keyword static. Static methods can
access only static fields, methods. To access static methods there is no need to
instantiate the class, you can do it just using the class name as

15
Static Blocks

These are a block of codes with a static keyword. In general, these are used to
initialize the static members. JVM executes static blocks before the main
method at the time of class loading.

Inheritance
It is the mechanism in java by which one class is allowed to inherit the
features(fields and methods) of another class.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

16
Terms used in Inheritance
o Class:

A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.

o 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.

o 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.

o 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 increase the
functionality.

In the terminology of Java, a class which is inherited is called a parent or


superclass, and the new class is called child or subclass.

17
Inheritance Example

Programmer is the subclass and Employee is the superclass. The relationship


between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.

Example:

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);
}
}

Output:

18
Types of inheritance in java

 Single Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Multiple Inheritance
 Hybrid Inheritance

Single Inheritance

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.

Example:

class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
19
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}

Multilevel Inheritance
 When there is a chain of inheritance, it is known as multilevel
inheritance.
 In Multilevel Inheritance, a derived class will be inheriting a base class
and as well as the derived class also act as the base class to other class.

20
Example
BabyDog class inherits the Dog class which again inherits the Animal class, so
there is a multilevel inheritance.

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();
}
}

21
Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for
more than one subclass.

Example
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()

22
{
System.out.println("meowing...");
}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
}
}

Multiple inheritance(Through Interface)

 In Multiple inheritances, one class can have more than one superclass
and inherit features from all parent classes.
 Java does not support multiple inheritances with classes. In java, we
can achieve multiple inheritances only through Interfaces.

To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

23
Consider a scenario where A, B, and C are three classes. The C class inherits A
and B classes. If A and B classes have the same method and you call it from
child class object, there will be ambiguity to call the method of A or B class.

Example:

class A
{
void msg()
{
System.out.println("Hello");
}
}
class B
{
void msg()

System.out.println("Welcome");
}
}
class C extends A,B
{
public static void main(String args[])
{
C obj=new C();
obj.msg();
}
}

Example 2:

import java.io.*;

24
import java.lang.*;
import java.util.*;

interface one
{
public void print_geek();
}

interface two
{
public void print_for();
}

interface three extends one, two


{
public void print_geek();
}
class child implements three
{
@Override public void print_geek()
{
System.out.println("Geeks");
}

public void print_for()


{
System.out.println("for");
}
}

public class Main


{
public static void main(String[] args)
{
child c = new child();
c.print_geek();
c.print_for();

25
c.print_geek();
}
}

Hybrid Inheritance(Through Interfaces):

 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.

The composition of single and multiple inheritance represents


the hybrid inheritance.

Example:

In this program, we have taken the example of Human body that performs
different functionalities like eating, walking, talking, dancing etc. Human body
may be either Male or Female. So, Male and Female are the two interfaces of
the HumanBody class. Both the child class inherits the functionalities of the
HumanBody class that represents the single Inheritance.
26
Suppose, Male and Female may have child. So, the Child class also inherits the
functionalities of the Male, Female interfaces. It represents
the multiple inheritance.

class HumanBody
{
public void displayHuman()
{
System.out.println("Method defined inside HumanBody class");
}
}

interface Male
{
public void show();
}
interface Female
{
public void show();
}
public class Child extends HumanBody implements Male, Female
{
public void show()
{
System.out.println("Implementation of show() method defined in interfac
esMale and Female");
}
public void displayChild()
{
System.out.println("Method defined inside Child class");
}
public static void main(String args[])
{
Child obj = new Child();
System.out.println("Implementation of Hybrid Inheritance in Java");
obj.show();
obj.displayChild();
}
27
}

Output:

Implementation of Hybrid Inheritance in Java


Implementation of show() method defined in interfaces Male and Female
Method defined inside Child class

Super Keyword
 The super keyword in Java is a reference variable which is used to refer
immediate parent class object.

 Whenever you create the instance of subclass, an instance of parent class


is created implicitly which is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

28
1) super is used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent
class. It is used if parent class and child class have same fields.class Animal{

String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}

29
2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be
used if subclass contains the same method as parent class. In other words, it is
used if method is overridden.

Example:

class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()

{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}

30
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}

In the above example Animal and Dog both classes have eat() method if we call
eat() method from Dog class, it will call the eat() method of Dog class by
default because priority is given to local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor.

Example:

class Anima
l{
Animal()
{
System.out.println("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
31
super();
System.out.println("dog is created");
}
}
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}
}

Note: super() is added in each class constructor automatically by compiler if


there is no super() or this().

As we know well that default constructor is provided by compiler automatically


if there is no constructor. But, it also adds super() as the first statement.

Another example of super keyword where super() is provided by the


compiler implicitly.

class Animal
{
Animal()

32
{
System.out.println("animal is created");

}
}
class Dog extends Animal
{
Dog()
{
System.out.println("dog is created");
}
}
class TestSuper4

{
public static void main(String args[])
{
Dog d=new Dog();
}
}

Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method


that has been declared by one of its parent class, it is known as method
overriding.

33
Usage of Java Method Overriding
o Method overriding is used to provide the specific implementation of a
method which is already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


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).

Example of method overriding

In this example, we have defined the run method in the subclass as defined in
the parent class but it has some specific implementation. The name and
parameter of the method are the same, and there is IS-A relationship between
the classes, so there is method overriding.

class Vehicle
{
void run()

{
System.out.println("Vehicle is running");
}
}
class Bike2 extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}

public static void main(String args[])


{
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}

34
}

A real example of Java Method Overriding

Consider a scenario where Bank is a class that provides functionality to get the
rate of interest. However, the rate of interest varies according to banks. For
example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of
interest.

Example:

Java Program to demonstrate the real scenario of Java Method Overriding

class Bank

{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank
{
int getRateOfInterest(){return 8;}
}

class ICICI extends Bank


35
{
int getRateOfInterest()

{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
}
}
//Test class to create objects and call the methods
class Test2
{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

Can we override static method?

No, a static method cannot be overridden. It can be proved by runtime


polymorphism

36
Why can we not override static method?

It is because the static method is bound with class whereas instance method is
bound with an object. Static belongs to the class area, and an instance belongs to
the heap area.

Difference between method overloading and method overriding in java

Method Overloading Method Overriding


Method overloading is used to Method overriding is used to provide
increase the readability of the the specific implementation of the
program. method that is already provided by its
super class.
Method overloading is Method overriding occurs in two
performed within class classes that have IS-A (inheritance)
relationship.
In case of method In case of method
overloading, parameter must be overriding, parameter must be same.
different.
Method overloading is the example Method overriding is the example
of compile time polymorphism. of run time polymorphism.
In java, method overloading can't be Return type must be same or
performed by changing return type of covariant in method overriding.
the method only. Return type can be
same or different in method
overloading. But you must have to
change the parameter.

Java Method Overloading example


class OverloadingExample
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
37
}

Java Method Overriding example


class Animal
{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
}

Dynamic Method Dispatch


Runtime polymorphism or Dynamic Method Dispatch is a process in which
a call to an overridden method is resolved at runtime rather than compile-time.

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.

class A{}
class B extends A{}
A a=new B();//upcasting
For upcasting, we can use the reference variable of class type or an interface type.
38
Example:
interface I
{
}
class A
{
}
class B extends A implements I
{
}

Example of Java Runtime Polymorphism

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.

class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splendor();//upcasting
b.run();
}
}

39
Java Runtime Polymorphism Example: Bank

Consider a scenario where Bank is a class that provides a method to get the rate
of interest. However, the rate of interest may differ according to banks. For
example, SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7% rate
of interest.

class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());

40
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}

Java Runtime Polymorphism Example: Animal


class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
}
class Cat extends Animal{
void eat(){System.out.println("eating rat...");}
}
class Lion extends Animal{
void eat(){System.out.println("eating meat...");}
}
class TestPolymorphism3{
public static void main(String[] args){
Animal a;
a=new Dog();
a.eat();
a=new Cat();
a.eat();
a=new Lion();
a.eat();
}}

41
Abstract class

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
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.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have


abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.

42
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the
body of the method.

Example of abstract class

1. abstract class A{}

Abstract Method in Java

A method which is declared as abstract and does not have implementation is


known as an abstract method.

Example of abstract method

abstract void printStatus();

43
Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method
run. Its implementation is provided by the Honda class.

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();
}
}

Example:

In this example, Shape is the abstract class, and its implementation is provided
by the Rectangle and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the
end user), and an object of the implementation class is provided by the factory
method.

A factory method is a method that returns the instance of the class. We will
learn about the factory method later.

In this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.

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");}
44
}
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 a real scenario, object is provided through method, e.g.,
getShape() method
s.draw();
}
}

Abstract class having constructor, data member and methods

An abstract class can have a data member, abstract method, method body (non-
abstract method), constructor, and even main() method.

abstract class Bike{


Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}

45
}

Final Keyword
The final keyword in java is used to restrict the user. The java final keyword
can be used in many context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have
no value it is called blank final variable or uninitialized final variable. It can be
initialized in the constructor only. The blank final variable can be static also
which will be initialized in the static block only. We will have detailed learning
of these.

Java final variable

If you make any variable as final, you cannot change the value of final
variable(It will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value
can never be changed.

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}

46
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}

Java final method

If you make any method as final, you cannot override it.

Example of final method


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();
}
}

Using final with inheritance


During inheritance, we must declare methods with the final keyword for
which we are required to follow the same implementation throughout all the
derived classes.
Example: 1
class Bike{
final void run(){System.out.println("running...");}
}
47
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}

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 the classes and interfaces so that they can
be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

48
Example:
This file can be saved as class_1.java and put it in the package folder.
package packages;
import java.io.*;
import java.util.Scanner;
public class class_1
{
int basic;
double da,ta,allowance,pf,it,detection,net_pay;
public class_1(int a)
{
basic=a;
da=basic*0.05;
ta=basic*0.08;
allowance=da+ta;
pf=basic*0.09;
it=basic*0.03;
detection=pf+it;
net_pay=(basic+allowance)-detection;
}
public void display()
{
System.out.println("\n Basic Salery:"+basic);

49
System.out.println("\n DA:"+da);
System.out.println("\n TA:"+ta);
System.out.println("\n Allowance:"+allowance);
System.out.println("\n Income tax:"+it);
System.out.println("\n Deduction:"+detection);
System.out.println("\n Netpay:"+net_pay);

}
}

This file can be saved as main_class.java


import packages.*;
import java.io.*;
import java.util.Scanner;
class main_class
{
public static void main(String args[])
{
class_1 obj=new class_1(5000);
obj.display();
}
}

OUTPUT:

50
How packages work?
Package names and directory structure are closely related.
For example if a package name is college.staff.cse, then there are three
directories, college, staff and cse such that cse is present in staff and staff is
present college. Also, the directory college is accessible
through CLASSPATH variable, i.e., path of parent directory of college is
present in CLASSPATH.
Package naming conventions :
Packages are named in reverse order of domain names, i.e.,
org.geeksforgeeks.practice. For example, in a college, the recommended
convention is college.tech.cse, college.tech.ee, college.art.history, etc.

Adding a class to a Package :


We can add more classes to a created package by using package name
at the top of the program and saving it in the package directory. We need a
new java file to define a public class, otherwise we can add the new class to
an existing .java file and recompile it.
Subpackages:
Packages that are inside another package are the subpackages. These
are not imported by default, they have to imported explicitly. Also, members
51
of a subpackage have no access privileges, i.e., they are considered as
different package for protected and default access specifiers.

Example :
import java.util.*;
util is a subpackage created inside java package.

How to access package from another package?

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.*


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();

52
}
}
Output:Hello

2) Using packagename.classname

If you import package.classname then only declared class of this package will
be accessible.

Example of package by import package.classname


//save by A.java

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

3) Using fully qualified name

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.

53
Example of package by import fully qualified name
//save by A.java
package pack;
public class A{
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

Subpackage in java

Package inside the package is called the subpackage. It should be created to


categorize the package further.

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.

Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
54
}

Importing Packages

To import java package into a class, we need to use java import keyword which
is used to access package and its classes into the java program.

Use import to access built-in and user-defined packages into your java source
file so that your class can refer to a class that is in another package by directly
using its name.

There are 3 different ways to refer to any class that is present in a different
package:

1. without import the package

2. import package with specified class

3. import package with all classes

Import the Specific Class

Package can have many classes but sometimes we want to access only specific
class in our program in that case, Java allows us to specify class name along
with package name. If we use import packagename.classname statement then
only the class with name classname in the package will be available for use.

Example:

In this example, we created a class Demo stored into pack package and in
another class Test, we are accessing Demo class by importing package name
with class name.

//save by Demo.java

package pack;

55
public class Demo {

public void msg() {

System.out.println("Hello");

//save by Test.java

package mypack;

import pack.Demo;

class Test {

public static void main(String args[])

Demo obj = new Demo();

obj.msg();

Hello

56
Interface
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.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

57
How to declare an interface?

An interface is declared by using the interface keyword. It provides total


abstraction; means all the methods in an interface are declared with the empty
body, and all the fields are public, static and final by default. A class that
implements an interface must implement all the methods declared in the
interface.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

Java Interface Example

In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.

interface printable{
void print();

58
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

Java Interface Example: Bank

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());
}}

59
60

You might also like