0% found this document useful (0 votes)
87 views

JV 1

The document discusses object-oriented programming (OOP) concepts like objects, classes, inheritance, polymorphism, abstraction, encapsulation, coupling, cohesion, association, aggregation, and composition. It provides examples and definitions for each concept. It also compares the advantages of OOP over procedure-oriented programming, including easier development and maintenance in OOP through concepts like data hiding.

Uploaded by

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

JV 1

The document discusses object-oriented programming (OOP) concepts like objects, classes, inheritance, polymorphism, abstraction, encapsulation, coupling, cohesion, association, aggregation, and composition. It provides examples and definitions for each concept. It also compares the advantages of OOP over procedure-oriented programming, including easier development and maintenance in OOP through concepts like data hiding.

Uploaded by

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

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

Apart from these concepts, there are some other terms which are used in Object-Oriented
design:

o Coupling
o Cohesion
o Association
o Aggregation
o Composition
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.

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.

Coupling
Coupling refers to the knowledge or information or dependency of another class. It arises
when classes are aware of each other. If a class has the details information of another class,
there is strong coupling. In Java, we use private, protected, and public modifiers to display
the visibility level of a class, method, and field. You can use interfaces for the weaker
coupling because there is no concrete implementation.

Cohesion
Cohesion refers to the level of a component which performs a single well-defined task. A
single well-defined task is done by a highly cohesive method. The weakly cohesive method
will split the task into separate parts. The java.io package is a highly cohesive package
because it has I/O related classes and interface. However, the java.util package is a weakly
cohesive package because it has unrelated classes and interfaces.

Association
Association represents the relationship between the objects. Here, one object can be
associated with one object or many objects. There can be four types of association between
the objects:

o One to One
o One to Many
o Many to One, and
o Many to Many

Let's understand the relationship with real-time examples. For example, One country can
have one prime minister (one to one), and a prime minister can have many ministers (one
to many). Also, many MP's can have one prime minister (many to one), and many ministers
can have many departments (many to many).

Association can be undirectional or bidirectional.

Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where
one object contains other objects as a part of its state. It represents the weak relationship
between objects. It is also termed as a has-a relationship in Java. Like, inheritance
represents the is-a relationship. It is another way to reuse objects.

Composition
The composition is also a way to achieve Association. The composition represents the
relationship where one object contains other objects as a part of its state. There is a strong
relationship between the containing object and the dependent object. It is the state where
containing objects do not have an independent existence. If you delete the parent object, all
the child objects will be deleted automatically.

Advantage of OOPs over Procedure-oriented


programming language
1) OOPs makes development and maintenance easier, whereas, in a procedure-oriented
programming language, it is not easy to manage if code grows as project size increases.

2) OOPs provides data hiding, whereas, in a procedure-oriented programming language,


global data can be accessed from anywhere.

Figure: Data Representation in Procedure-Oriented Programming


Figure: Data Representation in Object-Oriented Programming

3) OOPs provides the ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented Programming
language.

Variables

Local Variables
Local variables are declared inside a method. Individual methods can have the same variable name as another
method within a program. Local variables are only visible inside its individual method. Local variables are created
when the method is constructed and destroyed when the method is terminated.

publicclassVariableExample{
publicvoid Age() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
publicstaticvoid main(String args[]) {
VariableExamplelv = newVariableExample();
lv.Age();
}
}

Output: Puppy age is: 7

Parameter Variables
Parameter variables are declared and passed int o methods. After a parameter variable is declared, it is
implemented like a local variable. Therefore, a local variable and parameter variable cannot have the same name.
Keywords are not required for a parameter variable. However, the data type and variable name must be
surrounded by a parenthesis after the method name.

publicclassVariableExample
{
publicvoidsetMtgAmount(doublemtgAmount)
{
System.out.println("The mortgage payment amount is " + mtgAmount);
}
public static void main(String[] args)
{
VariableExamplepayment = newVariableExample ();
payment.setMtgAmount(99000);
}
}

Output: The mortgage payment amount is 99000.0

Instance Variables
Instance variables are declared inside a class, outside of a method, and can be optionally accessed after creating an
object. The values of an instance variable are unique to each object. Instance variable can be declared before or
after it is initialized with visibility to all methods in a class. Default values for a number is zero, for boolean the
default is false, and an object reference default is null.

Every time when you create an object memory will be allocated to the instance variable
for example
public class VariableExample{
int j = 20;
publicstaticvoid main(String[] args) {
InstanceVariable f = new InstanceVariable();
InstanceVariable f1 = new InstanceVariable();
}
}
in the above example we have an int variable with name “j” and created two objects for the class
so j variable will be allocated memory two time one for object f and one for object f1 Access
modifiers can be given for instance variables.

public classVariableExample
{
intyearsExist = 34;
public static void main(String[] args)
{
VariableExampleyears = newVariableExample ();
System.out.println("Org existed for " + years.yearsExist + " years");
}
}

Program Output: This organization has existed for 34 years


An instance variable can be accessed directly by calling the instance variable. However in this example, the
instance variable is accessed via ObjectReference due to the static method voidmain(String[] args). Line eight print
s the variable’s value by using the ObjectReference.InstanceVariable “years.yearsExist”.

3. Static variables:
Static variable (“static” Keyword = Class Variables)
If a variable is declared as static then the variable is said to be static variable. Example: static int y = 0;
A static variable is shared by all the object. If a variable is non static then for each object the memory is allocated
but for static variable only one time memory allocated and all the object uses that common memory location.
Static will be used in the memory management .JVM first looks for static variables and static methods before
starting programme execution from main method.

When a variable is declared with the keyword “static”, it’s called a “class variable”. As memory is allocated before
creating object static variable is can be accesses using class name rather that object name so static variables are
class variable not associated with object.

 It is a variable which belongs to the class and not to object (instance)


 Static variables are initialized only once, at the start of the execution. These variableswill be initialized
first, before the initialization of any instance variables.
 Class Variables are created when the program begins and destroyed when the program ends.
 A single copy to be shared by all instances of the class
 A static variable can be accessed directly by the class name and doesn’t need any object

public classVariableExample
{
static int numDays = 30;
public static void main(String[] args)
{

intnumDays = 50;
VariableExampledays = newVariableExample ();
System.out.println("Java can be mastered in " + VariableExample.numDays + " days");
System.out.println("Selenium can be mastered in " + days.numDays + " days");
System.out.println("Do you think you can master Java/Selenium " + numDays + "days");
}
}

Output:
Java can be mastered in 30 days
Selenium can be mastered in 30 days
Do you think you can master Java/Selenium in 50 days
public classVariableExample {

static inti = 0;
VariableExample() {
i = i + 1;
System.out.println(i);
}
public static void main(String[] args) {
VariableExamplet = newVariableExample ();
VariableExamplet1 = newVariableExample ();
}
}

Output: 1 ,2

public classVariableExample {

inti = 0;
VariableExample() {
i = i + 1;
System.out.println(i);
}
public static void main(String[] args) {
VariableExamplet = newVariableExample ();
VariableExamplet1 = newVariableExample ();
}
}

Output: 1 ,1

1: Final variables
Final variables are nothing but constants. We cannot change the value of a final variable once it
is initialized.

classFinal Var
{
final int MAX_VALUE=99;

voidmyMethod()
{
MAX_VALUE=101;
}

public static void main(String args[])


{
Final Varobj=newFinal Var ();
obj.myMethod();
}
}

Output:
Exceptionin thread "main" java.lang.Error: Unresolved compilation problem:
Thefinal field Final Var.MAX_VALUE cannot be assigned

2) Final method
A final method cannot be overridden. Which means even though a sub class can call the final
method of parent class without any issues but it cannot override it.

classFMethod{
finalvoid demo()
{
System.out.println("FMethod Class Method");
}
}
classFSubextendsFMethod
{
voiddemo ()
{
System.out.println("ABC Class Method");
}
public static void main(String args[]){
FSubobj= newFSub();
obj.demo();
}
}

Output: Compilation error, Cannot override the final method from FMethod

3) Final class
If we declare a class as final we cannot extend a final class.

final classFClass {
}

classFsubextendsFClass {
void demo() {
System.out.println("My Method");
}

public static void main(String args[]) {


Fsubobj = newFsub();
obj.demo();
}
}

Output: The type Fsub cannot subclass the final class FClass

What is THIS Keyword in Java?


Keyword THIS is a reference variable in Java that refers to the current object.
The various usages of 'THIS' keyword in Java are as follows:
 It can be used to refer current class instance variable
 It can be used to invoke or initiate current class constructor
 It can be passed as an argument in the method call
 It can be passed as argument in the constructor call
 It can be used to return the current class instance
 "This" is a reference to the current object, whose method is being called upon.
 You can use "this" keyword to avoid naming conflicts in the method/constructor of your instance/object.

Understand 'this' keyword with an example.


1. Class: class Account
2. Instance Variable: a and b
3. Method Set data: To set the value for a and b.
4. Method Show data: To display the values for a and b.
5. Main method: where we create an object for Account class and call methods set data and show data.

class Account{
inta;
intb;

public void setData(int c ,int d){


a = c;
b = d;
}
public void showData(){
System.out.println("Value of A ="+a);
System.out.println("Value of B ="+b);
}
public static void main(String args[]){
Account obj = newAccount();
obj.setData(2,3);
obj.showData();
}
}

Output: Value of A =0 Value of B =0

In the method Set data, the arguments (local variables) are declared as a and b, while the instance variables are
also named as a and b(Below left image)

During execution, the compiler is confused. Whether "a" on the left side of the assigned operator is the instance
variable or the local variable. Hence, it does not set the value of 'a' or ‘b’ when the method set data is called.
The solution is the "THIS" keyword.Append both 'a' and 'b' with the "this" keyword followed by a dot (.)
operator.During code execution when an object calls the method 'setdata'. The keyword 'this' is replaced by the
object handler "obj." (above right image)

class Account{
inta;
intb;

public void setData(int c ,int d){


this.a = c;
this.b = d;
}
public void showData(){
System.out.println("Value of A ="+a);
System.out.println("Value of B ="+b);
}
public static void main(String args[]){
Account obj = newAccount();
obj.setData(2,3);
obj.showData();
}
}

Output:Valueof A =2 Value of B =3

If local variables (formal arguments) and instance variables are same, there is need to use this keyword
If local variables (formal arguments) and instance variables are different, there is no need to use this keyword

Suppose you are smart enough to choose different names for your instance variable and methods arguments. But
this time around, you create two objects of the class, each calling the set data method.
How the compiler will determine whether it is supposed to work on instance variable of object 1 or object 2?

class Account{
inta;
intb;

public void setData(int c ,int d){


this.a = c;
this.b = d;
}
public void showData(){
System.out.println("Value of A ="+a);
System.out.println("Value of B ="+b);
}
public static void main(String args[]){
Account obj1 = newAccount();
Account obj2 = newAccount();
obj1.setData(2,3);
obj2.setData(4,5);
obj1.showData();
obj2.showData();
}
}

Value of A =2 , B =3 , A =4 , B =5

The compiler implicitly appends the instance variable with "THIS" keyword.Such that when object 1 is calling the
set data method, an instance variable is appended by its reference variable.While object 2 is calling the set data
method, an instance variable of object 2 is modified.This process is taken care by the compiler itself .

Constructors in Java

Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of
statements(i.e. instructions) that are executed at time of Object creation.

Need of Constructor
Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height).
But when it comes to creating its object(i.e Box will now exist in computer’s memory), then can a box be there with
no value defined for its dimensions. The answer is no.
So constructors are used to assign values to the class variables at the time of object creation, either explicitly
done by the programmer or by Java itself (default constructor).

When is a Constructor called ?


Each time an object is created using new() keyword at least one constructor (it could be default constructor) is
invoked to assign initial values to the data members of the same class.
A constructor is invoked at the time of object or instance creation. For Example:
class Geek
{
.......
// A Constructor
new Geek() {}
.......
}
// We can create an object of the above class
// using the below statement. This statement
// calls above constructor.
Geek obj = newGeek();

Rules for writing Constructor:


 Constructor(s) of a class must has same name as the class name in which it resides.
 A constructor in Java can not be abstract, final , static and Synchronized.
 Access modifiers can be used in constructor declaration to control its access i.e which other class can call
the constructor.

Types of constructor
There are two type of constructor in Java:
1. No-argument constructor: A constructor that has no parameter is known as default constructor. If we don’t
define a constructor in a class, then compiler creates default constructor(with no arguments) for the class.
And if we write a constructor with arguments or no-arguments then the compiler does not create a default
constructor.
Default constructor provides the default values to the object like 0, null, etc. depending on the type.

// Java Program to illustrate calling a


// no-argument constructor

class Geek
{
intnum;
String name;

// this would be invoked while an object


// of that class is created.
Geek()
{
System.out.println("Constructor called");
}
}

class GFG
{
public static void main (String[] args)
{
// this would invoke default constructor.
Geek geek1 = newGeek();

// Default constructor provides the default


// values to the object like 0, null
System.out.println(geek1.name);
System.out.println(geek1.num);
}
}
Output :
Constructor called
null
0

2. Parameterized Constructor: A constructor that has parameters is known as parameterized constructor. If


we want to initialize fields of the class with your own values, then use a parameterized constructor.

// Java Program to illustrate calling of


// parameterized constructor.
class Geek
{
// data members of the class.
String name;
intid;

// constructor would initialize data members


// with the values of passed arguments while
// object of that class created.
Geek(String name, int id)
{
this.name = name;
this.id = id;
}
}

class GFG
{
public static void main (String[] args)
{
// this would invoke the parameterized constructor.
Geek geek1 = newGeek("adam", 1);
System.out.println("GeekName:" +geek1.name + " &GeekId :" + geek1.id);
}
}
Output:GeekName:adam&GeekId :1
Does constructor return any value?
There are no “return value” statements in constructor, but constructor returns current class instance. We can
write ‘return’ inside a constructor.
Constructor Overloading
Like methods, we can overload constructors for creating objects in different ways. Compiler differentiates
constructors on the basis of numbers of parameters, types of the parameters and order of the parameters.
// Java Program to illustrate constructor overloading
// using same task (addition operation ) for different
// types of arguments.

class Geek
{
// constructor with one argument
Geek(String name)
{
System.out.println("one " + "argument - String : " + name);
}

// constructor with two arguments


Geek(String name, int age)
{

System.out.println("two args:" + "String and Int eger:" + name + " "+ age);

// Constructor with one argument but with different


// type than previous..
Geek(longid)
{
System.out.println("1 arg : " + "Long : " + id);
}
}

class GFG
{
Publicstaticvoidmain(String[] args)
{
// Creating the objects of the class named 'Geek'
// by passing different arguments

// Invoke the constructor with one argument of


// type 'String'.
Geek geek2 = newGeek("Shikhar");

// Invoke the constructor with two arguments


Geek geek3 = newGeek("Dharmesh", 26);

// Invoke the constructor with one argument of


// type 'Long'.
Geek geek4 = newGeek(325614567);
}
}

Output:
one argument - String : Shikhar
twoargs:String and Int eger:Dharmesh 26
1 arg : Long : 325614567

How constructors are different from methods in Java?


 Constructor(s) must have the same name as the class within which it defined while it is not necessary for the
method in java.
 Constructor(s) do not return any type while method(s) have the return type or void if does not return any
value.
 Constructor is called only once at the time of Object creation while method(s) can be called any numbers of
time.

Why Constructors are not inherited in Java?

Constructor is a block of code that allows you to create an object of class and has same name as class with no
explicit return type.

Whenever a class (child class) extends another class (parent class), the sub class inherits state and behavior in the
form of variables and methods from its super class but it does not inherit constructor of super class because of
following reasons:

Constructors are special and have same name as class name. So if constructors were inherited in child class then
child class would contain a parent class constructor which is against the constraint that constructor should have
same name as class name. For example see the below code:

class Parent {
public Parent()
{
}

public void print ()


{
}
}

public class Childextends Parent {


publicParent()
{
}
public void print ()
{
}

public static void main(String[] args)


{
Child c1 = newChild(); // allowed
Child c2 = newParent(); // not allowed
}
}
If we define Parent class constructor inside Child class it will give compile time error for return type and consider it
a method. But for print method it does not give any compile time error and consider it a overriding method.

Now suppose if constructors can be inherited then it will be impossible to achieving encapsulation. Because by
using a super class’s constructor we can access/initialize private members of a class.

A constructor cannot be called as a method. It is called when object of the class is created so it does not make
sense of creating child class object using parent class constructor notation. i.e. Child c = new Parent();

A parent class constructor is not inherited in child class and this is why super() is added automatically in child class
constructor if there is no explicit call to super or this

Inheritance
A class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a
subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the
Superclass and adds its own, unique elements. To inherit a class, you simply incorporate the definition of one class
into another by using the extends keyword.

// Create a superclass.
class A {
inti, j;
voidshowij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
intk;
voidshowk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
classSimpleInheritance {
publicstaticvoid main(String args[]) {
A superOb = newA();
B subOb = newB();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}

Output :
Contents of superOb:
i and j: 10 20

Contents of subOb:
i and j: 7 8
k: 9

Sum of i, j and k in subOb:


i+j+k: 24

Even though A is a superclass for B, it is also a completely independent, stand-alone class.

A class member that has been declared as private will remain private to its class. It is not accessible by any code
outside its class, including subclasses.

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

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.

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

Output: To access the parent property, we need to use super keyword.


black
white

super.Method

Note: Multiple inheritance is not supported in Java through class.

Polymorphism
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

In Java it is possible to define two or more methods within the same class that share the same name, as long as their
parameter declarations are different.

Advantage of method overloading


Method overloading increases the readability of the program.

There are two ways to overload the method in java

 By changing number of arguments


 By changing the data type

In java, Method Overloading is not possible by changing the return type of the method only.

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.

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

class Adder{
staticint add(inta,intb){returna+b;}
staticint add(inta,intb,intc){returna+b+c;}
}
class TestOverloading1{
publicstaticvoid main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

Output:
22
33
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.

class Adder{
staticint add(inta, intb){returna+b;}
staticdouble add(doublea, doubleb){returna+b;}
}
class TestOverloading2{
publicstaticvoid main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9

Q) Why Method Overloading is not possible by changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only because of ambiguity.
Let's see how ambiguity may occur:

class Adder{
staticintadd(inta,intb){returna+b;}
staticdoubleadd(inta,intb){returna+b;}
}
class TestOverloading3{
publicstaticvoid main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}

Output:
Compile Time Error: method add(int,int) is already defined in class Adder

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.

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.

Usage of Java Method Overriding


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

Rules for Java Method Overriding


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

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.Method invocation is determined by the JVM not compiler, it is
known as runtime polymorphism
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

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

class ICICI extends Bank{


intgetRateOfInterest(){return 7;}
}
class AXIS extends Bank{
intgetRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
classOverrideBank{
publicstaticvoid main(String args[]){
SBI s=newSBI();
ICICI i=newICICI();
AXIS a=newAXIS();
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

Can we override static method?


No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later.
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.

Can we override java main method?


No, because the main is a static method.

No. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to


readability of the program. provide the specific
implementation of the method
that is already provided by its
super class.

2) Method overloading is performed within class. Method overriding occurs in two


classes that have IS-A
(inheritance) relationship.

3) In case of method overloading, parameter In case of method


must be different. overriding, parameter must be
same.

4) Method overloading is the example of compile Method overriding is the example


time polymorphism. of run time polymorphism.

5) In java, method overloading can't be Return type must be same or


performed by changing return type of the covariant in method overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.

Java Abstraction

Abstract class in Java

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

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)

2. Interface (100%)

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

 An abstract class must be declared with an abstract keyword.


 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the method.
 If there is an abstract method in a class, that class must be abstract.
 If you are extending an abstract class that has an abstract method, you must either provide the
implementation of the method or make this class abstract.
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();
}
}

The type subclass must implement the inherited abstract method of base class

abstract class Bank{


abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}

class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}

Rate of Interest is: 7 %


Rate of Interest is: 8 %

Another real scenario of abstract class

The abstract class can also be used to provide some implementation of the interface. In such case, the
end user may not be forced to override all the methods of the interface.
interface A{
void a();
void b();
void c();
void d();
}

abstract class B implements A{


public void c(){System.out.println("I am c");}
}

class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}

class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}

Output: I am a
I am b
I am c
I am d

Why use Java interface?


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

It is used to achieve abstraction.


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

You might also like