Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

java programming notes unit 3-4

This document covers key concepts in Java programming, including arrays, methods, constructors, and access control. It explains how to declare and process arrays, the purpose and types of constructors, and the structure of methods, including call by value. Additionally, it discusses static fields and methods, as well as access modifiers that control the visibility of class members.

Uploaded by

vvarshini279
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

java programming notes unit 3-4

This document covers key concepts in Java programming, including arrays, methods, constructors, and access control. It explains how to declare and process arrays, the purpose and types of constructors, and the structure of methods, including call by value. Additionally, it discusses static fields and methods, as well as access modifiers that control the visibility of class members.

Uploaded by

vvarshini279
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Unit 3

Arrays, Methods and Constructors

Arrays

Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:

dataType[] arrayRefVar; // preferred way. or


dataType arrayRefVar[]; // works but not preferred way.

Note: The style dataType[] arrayRefVar is preferred. The style dataType


arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate
C/C++ programmers.
Example:

The following code snippets are examples of this syntax:


double[] myList; or
double myList[];

Creating Arrays:
You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];

The above statement does two things:

 It creates an array using new dataType[arraySize];

 It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is, they
start from 0 to arrayRefVar.length-1.

Example:
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:

double[] myList = new double[10];

Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.

Processing Arrays:
When processing array elements, we often use either for loop or for each loop because all of the
elements in an array are of the same type and the size of the array is known.

Example:
Here is a complete example of showing how to create, initialize and process arrays:

public class TestArray


{
public static void main(String[] args)
{ double[] myList = {1.9, 2.9, 3.4,
3.5};
// Print all the array elements
for (int i = 0; i < myList.length;
i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length;
i++) { total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest
element double max =
myList[0];
for (int i = 1; i < myList.length; i++)
{ if (myList[i] > max) max =
myList[i];
}
System.out.println("Max is " + max);
}
}
This would produce the following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

public class TestArray {


public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements

for (double element: myList) { System.out.println(element);


}}}

JAVA PROGRAMMING Page 4


Constructors

Constructor in java is a special type of method that is used to initialize the object. Java
constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.

There are basically two rules defined for the constructor.


1. Constructor name must be same as its class name

2. Constructor must have no explicit return type

Types of java constructors


There are two types of constructors:

1. Default constructor (no-arg constructor)

2. Parameterized constructor

Java Default Constructor

A constructor that have no parameter is known as default constructor.

Syntax of default constructor:


1. <class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){ Bike1 b=new Bike1();

JAVA PROGRAMMING Page 5


}}
Output: Bike is created

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
class Student4{
int id; String name;
Student4(int i,String n){ id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[])


{ Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}}

Output:

111 Karan
222 Aryan

Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.

Example of Constructor Overloading


class Student5{
int id; String name; int age;

JAVA PROGRAMMING Page 6


Student5(int i,String n){ id = i;
name = n;
}
Student5(int i,String n,int a){ id = i;
name = n; age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){ Student5 s1 = new Student5(111,"Karan"); Student5 s2


= new Student5(222,"Aryan",25); s1.display();

s2.display();
}}

Output:

111 Karan 0
222 Aryan 25

Java Copy Constructor

There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++. There are many ways to copy the values of one object into another in
java. They are:
 By constructor
 By assigning the values of one object into another

 By clone() method of Object class

In this example, we are going to copy the values of one object into another using java
constructor.
class Student6{
int id; String name;
Student6(int i,String n){ id = i;
name = n;

JAVA PROGRAMMING Page 7


}

Student6(Student6 s){ id = s.id;


name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){ Student6 s1 = new Student6(111,"Karan"); Student6 s2


= new Student6(s1); s1.display();
s2.display();
}}

Output:

111 Karan
111 Karan

Java -Methods

A Java method is a collection of statements that are grouped together to perform an operation.
When you call the System.out.println() method, for example, the system actually executes
several statements in order to display a message on the console.

Creating Method

Considering the following example to explain the syntax of a method −

Syntax

public static int methodName(int a, int b) {


// body
}

Here,

 public static − modifier

JAVA PROGRAMMING Page 8


 int − return type

 methodName − name of the method

 a, b − formal parameters

 int a, int b − list of parameters

Method definition consists of a method header and a method body. The same is shown in the
following syntax −

Syntax

modifier returnType nameOfMethod (Parameter List) {


// method body
}

The syntax shown above includes −

 modifier − It defines the access type of the method and it is optional to use.

 returnType − Method may return a value.

 nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
 Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.

 method body − The method body defines what the method does with the
statements.

Call by Value and Call by Reference in Java

There is only call by value in java, not call by reference. If we call a method passing a value, it
is known as call by value. The changes being done in the called method, is not affected in the

JAVA PROGRAMMING Page 9


calling method.

Example of call by value in java

In case of call by value original value is not changed. Let's take a simple example:

class Operation{

int data=50;

void change(int data){

data=data+100;//changes will be in the local variable only

public static void main(String args[]){ Operation op=new Operation();


System.out.println("before change "+op.data); op.change(500);
System.out.println("after change "+op.data);

Output:before change 50
after change 50
}

In Java, parameters are always passed by value. For example, following program prints i = 10,
j = 20.
// Test.java class Test {
// swap() doesn't swap i and j
public static void swap(Integer i, Integer j)
{ Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void main(String[] args) { Integer i = new Integer(10);
Integer j = new Integer(20); swap(i, j);
System.out.println("i = " + i + ", j = " + j);
}

JAVA PROGRAMMING Page 10


}

Static Fields and Methods

The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.

The static can be:

 variable (also known as class variable)

 method (also known as class method)

 block

 nested class

Java static variable

If you declare any variable as static, it is known static variable.

o The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of students etc.

o The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable


It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable

class Student{

int rollno;

JAVA PROGRAMMING Page 11


String name;

String college="ITS";

5. }

Example of static variable

//Program of static variable

class Student8{

int rollno;
String name;

static String college ="ITS"; Student8(int r,String n){ rollno = r;


name = n;

void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){ Student8 s1 = new Student8(111,"Karan");


Student8 s2 = new Student8(222,"Aryan");

s1.display();

s2.display();

}}

Output:111 Karan ITS

222 Aryan ITS

Java static method

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than object of a class.

o A static method can be invoked without the need for creating an instance of a class.

JAVA PROGRAMMING Page 12


o static method can access static data member and can change the value of it.

Example of static method

//Program of changing the common property of all objects(static field).

class Student9{ int rollno; String name;


static String college = "ITS";

static void change(){ college = "BBDIT";


}

Student9(int r, String n){ rollno = r;


name = n;
}

void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[])

Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();

s3.display();

Output:111 Karan BBDIT


222 Aryan BBDIT
333 Sonoo BBDIT
}}

JAVA PROGRAMMING Page 13


Java static block

o Is used to initialize the static data member.

o It is executed before main method at the time of class loading.

Example of static block class A2{


static{System.out.println("static block is invoked");} public static void main(String args[]){
System.out.println("Hello main");

Output: static block is invoked


Hello main
}}

Access Control

Access Modifiers in java


There are two types of modifiers in java: access modifiers and non-access modifiers. The
access modifiers in java specifies accessibility (scope) of a data member, method, constructor
or class.

There are 4 types of java access modifiers:


 private

 default

 protected

 public

1. private access modifier

The private access modifier is accessible only within class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the
JAVA PROGRAMMING Page 14
class, so there is compile time error.
class A{

private int data=40;

private void msg(){System.out.println("Hello java");} }

public class Simple{

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


System.out.println(obj.data);//Compile Time Error obj.msg();//Compile Time Error
}}

2) default access modifier

If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
//save by A.java
package pack;
class A{
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();//Compile Time Error

obj.msg();//Compile Time Error } }

JAVA PROGRAMMING Page 15


In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

3) protected access modifier

The protected access modifier is accessible within package and outside the package but
through inheritance only. The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.

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

//save by B.java

package mypack;

import pack.*;

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

}}

Output:Hello

JAVA PROGRAMMING Page 16


4) public access modifier

The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Example of public access modifier

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

}}

Output:Hello

JAVA PROGRAMMING Page 17


Understanding all java access modifiers

Let's understand the access modifiers by a simple table.

Access within within outside package outside


Modifier class package by subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

This Keyword In Java

Usage of java this keyword

Here is given the 6 usage of java this keyword.

 this can be used to refer current class instance variable.


 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.

 this can be passed as an argument in the method call.


 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.

class Student
{ int rollno; String name; float fee;
Student(int rollno,String name,float fee){

JAVA PROGRAMMING Page 18


this.rollno=rollno; this.name=name; this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){ Student s1=new Student(111,"ankit",5000f); Student
s2=new Student(112,"sumit",6000f); s1.display();
s2.display();
}}

Output:
111 ankit 5000
112 sumit 6000

Difference between constructor and method in java

Java Constructor Java Method

Constructor is used to initialize the Method is used to expose behaviour of an


state of an object. object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default Method is not provided by compiler in


constructor if you don't have any any case.
constructor.

Constructor name must be same as the Method name may or may not be same as
class name. class name.

There are many differences between constructors and methods. They are given belo

JAVA PROGRAMMING Page 19


Constructor Overloading in Java

Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.

Example of Constructor Overloading

class Student5{ int id; String name; int


age;

Student5(int i,String n){ id = i;


name = n;

Student5(int i,String n,int a){ id = i;


name = n; age=a;
}

void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[])


{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();

Output:

111 Karan 0
222 Aryan 25

JAVA PROGRAMMING Page 20


Method Overloading in java

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.
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. 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));
}}
Output:

22
33

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.
Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in java that
JAVA PROGRAMMING Page 21
calls itself is called recursive method.
Java Recursion Example 1: Factorial Number
public class RecursionExample3 {

static int factorial(int n){

if (n == 1) return 1; else
return(n * factorial(n-1));

}}

public static void main(String[] args) { System.out.println("Factorial of 5 is: "+factorial(5));


}}

Output:

Factorial of 5 is: 120

JAVA PROGRAMMING Page 22


Unit 4

Java OOPs Concepts, Interface & Abstract Classes

OOPs (Object-Oriented Programming System)

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object

Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an address and takes up
some space in memory. Objects can communicate without knowing the details of each other's
data or code. The only necessary thing is the type of message accepted and the type of response
returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.

Class

Collection of objects is called class. It is a logical entity.

JAVA PROGRAMMING Page 23


A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.

Inheritance

When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

If one task is performed in different ways, it is known as polymorphism. For example: to


convince the customer differently, to draw something, for example, shape, triangle, rectangle,
etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks woof,
etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing. In Java, we use abstract class and interface to
achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines. A java class is the example of
encapsulation. Java bean is the fully encapsulated class because all the data members are
private here.

JAVA PROGRAMMING Page 24


Inheritance in Java

Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object. Inheritance represents the IS-A relationship, also known as
parent-child relationship.

Why use inheritance in java


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

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.

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

Programmer salary is:40000.0


Bonus of programmer is:10000

JAVA PROGRAMMING Page 25


Types of inheritance in java

Single Inheritance Example

File: TestInheritance.java

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

JAVA PROGRAMMING Page 26


Multilevel Inheritance Example

File: TestInheritance2.java

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

Output:

weeping...
barking...
eating...

JAVA PROGRAMMING Page 27


Hierarchical Inheritance Example

File: TestInheritance3.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){ Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Output:

meowing...
eating...

Member access and Inheritance

A subclass includes all of the members of its super class but it cannot access those members of
the super class that have been declared as private. Attempt to access a private variable would
cause compilation error as it causes access violation. The variables declared as private, is only
accessible by other members of its own class. Subclass have no access to it.

JAVA PROGRAMMING Page 28


super keyword in java

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


 super can be used to refer immediate parent class instance variable.

 super can be used to invoke immediate parent class method.

 super() can be used to invoke immediate parent class constructor.

super is used to refer immediate parent class instance variable.

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

}}

Output:

JAVA PROGRAMMING Page 29


black
white

Final Keyword in Java

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

 variable

 method

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

Object class in Java

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. Notice that parent class reference variable can refer the child class object,
know as upcasting.

Let's take an 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:

1. Object obj=getObject();//we don't know what object will be returned from this method

The Object class provides some common behaviors to all the objects such as object can be

JAVA PROGRAMMING Page 30


compared, object can be cloned, object can be notified etc.

Method Overriding in Java

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

 Method overriding is used to provide specific implementation of a method that is


already provided by its super class.

 Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


 method must have same name as in the parent class
 method must have same parameter as in the parent class.
 must be IS-A relationship (inheritance).

Example of 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();
obj.run();
}

Output:Bike is running safely

1. class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}

JAVA PROGRAMMING Page 31


class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
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());
}}

Output:
SBI Rate of Interest: 8

ICICI Rate of Interest: 7


AXIS Rate of Interest: 9

Abstract class in Java

A class that is declared with abstract keyword is known as abstract class in java. It can have
abstract and non-abstract methods (method with body). It needs to be extended and its method
implemented. It cannot be instantiated.

Example abstract class


1. abstract class A{}

abstract method

1. abstract void printStatus();//no body and abstract


Example of abstract class that has abstract method

abstract class Bike{

abstract void run();

JAVA PROGRAMMING Page 32


}

class Honda4 extends Bike{

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

public static void main(String args[]){ Bike obj = new Honda4();


obj.run();

1. }

running safely..

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.

Java Interface also represents IS-A relationship. It cannot be instantiated just like abstract
class. 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.

Internal addition by compiler

Understanding relationship between classes and interfaces


/Interface declaration: by first user
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
JAVA PROGRAMMING Page 33
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();
}}

Output:drawing circle

Multiple inheritance in Java by interface


interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print()
{System.out.println("Hello");}
public void show()
{System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}}

Output:Hello
Welcome

JAVA PROGRAMMING Page 34


Abstract class Interface

1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods. Since Java 8, it can have default and
static methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.

5) The abstract keyword is used to The interface keyword


declare abstract class.

6) Example: Example:
public abstract class shape public interface Drawable{
{ void draw();
Public abstract void draw(); }
}

Difference between Method overloading and overriding

Method Overloading Method Overriding

Method overloading is a compile-time Method overriding is a run-time


polymorphism. polymorphism.

Method overriding is used to grant the


Method overloading helps to increase the specific implementation of the method
readability of the program. which is already provided by its parent
class or superclass.

It is performed in two classes with


It occurs within the class.
inheritance relationships.

Method overloading may or may not require Method overriding always needs
inheritance. inheritance.

JAVA PROGRAMMING Page 35


Method Overloading Method Overriding

In method overloading, methods must have In method overriding, methods must


the same name and different signatures. have the same name and same signature.

In method overloading, the return type can or


In method overriding, the return type
can not be the same, but we just have to
must be the same or co-variant.
change the parameter.

Static binding is being used for overloaded Dynamic binding is being used for
methods. overriding methods.

Private and final methods can’t be


Private and final methods can be overloaded.
overridden.

The argument list should be different while The argument list should be the same in
doing method overloading. method overriding.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented


programming language, we can declare that everything present in the Java programming
language rotates throughout the Objects, except for some of the primitive data types and
primitive methods for integrity and simplicity. There are no solely functions present in a
programming language called Java. Functions in the Java programming language are part of a
class, and if someone wants to use them, they have to use the class or object of the class to call
any function.

Java Functional Interfaces

A functional interface is an interface that contains only one abstract method. They can have
only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to
represent the instance of a functional interface. A functional interface can have any number of
default methods. Runnable, ActionListener, and Comparable are some of the examples of
functional interfaces.

// Java program to demonstrate functional interface

JAVA PROGRAMMING Page 36


class Test {

public static void main(String args[])

// create anonymous inner class object

new Thread(new Runnable() {

@Override public void run()

System.out.println("New thread created");

}).start();

JAVA PROGRAMMING Page 37

You might also like