java Unit 2
java Unit 2
Method Declaration
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:
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:
Parameter List:
2
If the method has no parameter, left the parentheses blank.
Method Body:
Types of Method
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.
Example
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:
Output 2:
Example:2
5
Static Method
Example:
6
Instance Method
Example:
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
Example
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.
It always declares in the abstract class. It means the class itself must be
abstract if it has abstract method.
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
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));
}
}
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));
}
}
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");
}
}
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();
}
}
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.
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.
16
Terms used in Inheritance
o Class:
o Reusability:
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.
17
Inheritance Example
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
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();
}
}
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();
}
25
c.print_geek();
}
}
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:
Super Keyword
The super keyword in Java is a reference variable which is used to refer
immediate parent class object.
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.
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();
}
}
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.
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
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");
}
34
}
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:
class Bank
{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank
{
int getRateOfInterest(){return 8;}
}
{
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());
}
}
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.
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
{
}
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.
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}
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());
}
}
41
Abstract class
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.
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.
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.
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.
An abstract class can have a data member, abstract method, method body (non-
abstract method), constructor, and even main() method.
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.
If you make any variable as final, you cannot change the value of final
variable(It will be constant).
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();
}
}
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.
1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
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);
}
}
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.
Example :
import java.util.*;
util is a subpackage created inside java 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.
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.
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
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
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:
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 {
System.out.println("Hello");
//save by Test.java
package mypack;
import pack.Demo;
class Test {
obj.msg();
Hello
56
Interface
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.
There are mainly three reasons to use interface. They are given below.
57
How to declare an interface?
Syntax:
interface <interface_name>{
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");}
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