Вы находитесь на странице: 1из 36

The languages like C,Pascal,Fortran etc are called Procedure Oriented

Programming languages since these languages, a programmer uses


procedures or functions to perform a task. When the programmer wants
to write a program, he will first divide the task into separate subtasks,
each of which is expressed as a function. So a C program generally
contains several functions which are called from main() function. This
approach is called Procedure Oriented Approach

Programmers have firmly followed Procedure Oriented Approach for


several decades, but his experience and observation teaches new
lessons, there is a sudden shift in software industry for a new approach
called Object Oriented Approach.
First of all, let us discuss the point why we need Object Oriented
Approach Already we have Procedure Oriented Approach.
Problems in Procedure Oriented Approach
In procedure oriented oriented approach, the programmer concentrate
on a specific task, and writes a set of functions to achieve it. When there
is another task to be added to the software, he would be writing another
set of functions. This means his concentration will be only on achieving
the tasks. He perceives the entire system as fragments of several tasks.
Whenever he wants to perform a new task he would be writing a new set
of functions, in most of the cases. If the programmer can construct the

new modules with the help of old modules, i.e, reusing the old modules,
programming will become easy. With this view, computer scientist have
thought about developing a new approach.
In this approach if the code size is reached 10000 lines before it reaches
the 1 lakh lines, suddenly he loses the control on the code.
For example to create software to send satellites into the sky and control
their operations from the ground stations, we may have to write millions
of lines of code. In such systems, procedure oriented approach is fails
and we need another approach.
This way of programming is un natural.
Because of the above reasons, computer scientists felt the need of a
new approach where the programming will have several modules, Each
module represents a class and the classes can be reusable and hence
maintenance of the code will become easy. This approach is a suitable
not only to develop bigger and complex applications but also to manage
them easily. Moreover this approach is built form a single root concept
object
Object Oriented Approach:

What is Objectorineted Approach?

Object oriented programming approach is a programming methodology


to design computer programs using classes and objects.
Features of Object Oriented Programming System(OOPS):

Class/Object
Encapsulation
Abstraction
Inheritance
Polymorphism

Class/Object:
Entire OOP methodology has been derived from a single root concept,
called object. An object is anything that really exists in the world and
can be distinguished from others.
Every object has properties and can perform certain actions. For
example, let us take a person whose name is srinu. srinu is an object
because he exists physically. He has properties like name,age,sex etc.
These properties can be represented by variables in our programming.
For example,
String name;
int age;
char sex;
Similarly, Raju can perform some actions like talking, walking, eating and
sleeping. we may not write code for such actions in programming. But
we can consider calculations and processing of data as actions. These
actions are performed by methods(functions). So an object contains
variables and methods.
It is possible that some objects may have similar properties and actions.
Such objects belong to same category called a class. For example, not
only raju, but also Ravi, Sita, Vijay, etc., persons have same properties
and actions. So they are all objects of same class, Person.
Observe that the Person will not exist physically, but objects exits
physically.

What is difference between a class and an object?


A class is a model for creating objects and does not exists physically. An
object is anything that exists physically. Both the class And objects
contain variables and methods.
Ex:
class Person{
//below are the called properties or instance variables
String name;
int age;
//below are the called the methods
void talk(){
}
void eat(){
}

}
Classes and Objects:
We know that a class is a model for creating objects. This means the
properties and actions of the objects are written in the class. Properties
are represented by variables and actions of the objects are represented
by methods. So a class contains variables and methods. The same
variables and methods are also available in the objects because they
are called from the class. These variables are also called Instance
variables because they are created inside the object(instance).
If we take a Person class, we can write code in the class that specifies
the properties and actions performed by any person. For example, a
person has properties like name.age, etc. similarly a Person can perform
actions like talking, walking, etc. so, the class Person contains these
properties and actions, as shown here:
Class Person{
//properties-Instance variables
String name;
int age;
void talk(){
System.out.println(Hello I am+name);
System.out.prinln(my age is+age);
}
}
Observe that the key word class is used to declare a class. After this
we should write your class name. In this class I declared two instance
variables and one method. This method is not returning any thing thats
why I gave void before the method name and this method is not taking
any input parameters. After this method in () I am not giving any input
parametrers.
class Demo{

public static void main(String args[]){


Person p =new Person(); // here p is called reference of Person class.
And new Person() is called object creation.
p.name=ravi; // here we are assigning some data(ravi) to the variable.
By using .(dot) operator we can refer the variables and methods in the
class
p.age=29; //here we are assigning some data(29) to the variable.
p.talk(); // by using . (dot)
}
}
O/p: Hello I am ravi
my age is 29
Object Creation:
We know that the objects are created on heap. After creation of an
object, JVM produces an unique reference number for the object form
the memory address of the object. This reference number is called
reference is also called hash code number.
To know the hashcode number(or reference) of an object. We can use
hashCode() method of Object Class as shown here:
Employee e1=new Employee();
System.out.println(e1.hashCode());
What is hashCode?
HashCode is unique identification number assigned to the objects by the
jvm. This hashCode is also called as reference number which is created
based on the location of the object in the memory. And is unique for all
the objects except Strings objects.

How you can find out hashCode of an object?


By using hashCode () method of Object class which is there in java.lang
package..
WAP(write a program) to create Person class and an object Raju to
Person class. Let us display the hash code number of the object, using
hashCode().

public class Person {


String name;
int age;
void talk(){
System.out.println("Hello my Name: "+name);
System.out.println("my age is: "+age);
}
public static void main(String[] args) {
Person p1=new Person();
p1.name="Raju";
p1.age=29;
p1.talk();
System.out.println(p1.hashCode());
}
}
O/P:
Hello my Name: Raju
my age is: 29
4072869
Here I am executing the same code but I am commenting some code we
will see what the difference in the output.

Person p1=new Person();


//p1.name="Raju";
//p1.age=29;
p1.talk();
System.out.println(p1.hashCode());
O/P:
Hello my Name: null
my age is: 0
4072869
If you are not assigning any values to the instance variables by default
jvm will give default values
Data types
Byte
Short
Int
Long
float
Double
String
Char
Boolean
Any class type

Default values jvm assigns


0
0
0
0
0.0
0.0
Null
A space
false
Null

Initializing the Instance variables:


It is the duty of the programmer to initialize the instance variables.
Depending on his requirements. They are various way to initialize a
instance variables of Person class. Here I am initializing the instance
variables outside the class. For this one I am creating a separate class
as Demo:

public class Demo {

public static void main(String[] args) {


Person p1=new Person();
p1.name="ravi";
p1.age=60;
p1.talk();
}
}
If you execute this code the output will be:
Hello my Name: ravi
my age is: 60
In this way we are initializing the instance variables of Person class in
some other class i.e Demo
This violates the security of data of Person class. If the Person class is
written by you and Demo class is written by somebody else. Somebody
directly accessing and assigning directly to your data and he can
overwrite the existing data.
Ex:
// in person class we are assign some data to the instance
variables
String name="srinu";
int age=30;
//In Demo class we are overwriting the data
Person p1=new Person();
p1.name="ravi";
p1.age=60;
p1.talk();
Protection of data is required. We have to protect the security
data.
private String name="srinu";
private int age=30;

private keyword does not allow name and age to be accessed


by any other class or program from outside. Thus it protects the
data. We also use public access for the methods to access the
methods outside the class.
Access Specifiers:
An access specifier is a keyword that specifies how to access
the members of a class or a class itself. We can use access
specifier before the class and its members
They are four types of access specifiers:
Private: private members of a class are not accessible outside
class. It is accessible only with in the class.
Public: it is use full to access outside the class and outside the
package also.
Protected: it is use full to access outside the class and within
the package.
Default: If you are not declaring anything java compiler uses
default access specifier. it is use full to access outside the class
and with in the package.
Can we declare class a private?
Ans: Not possible. We are declare class as a private java
complier cant execute your code
Suppose if you declare like this

public class Person {


private String name="srinu";
private int age=29;
void talk(){
System.out.println("Hello my Name: "+name);

System.out.println("my age is: "+age);


}
public static void main(String[] args) {
Person p1=new Person();
p1.talk();
System.out.println(p1.hashCode());
}
}

public class Demo {


public static void main(String[] args) {
Person p1=new Person();
p1.talk();
Person p2=new Person();
P2.talk();
}
}
O/P:
Hello my Name: srinu
my age is: 29
Hello my Name: srinu
my age is: 29
The above program gives the same output if you create n
objects.
This way of initialization is suitable for declaring constants. The
reason is constant values will not be changed even though we
create several objects
Final double pi=3.14159;
public class Person {
final double PI=3.14156;

void talk(){
System.out.println("my age is: "+PI);
}
public static void main(String[] args) {
Person p1=new Person();
p1.talk();
System.out.println(p1.hashCode());
}
}

public class Demo {


public static void main(String[] args) {
Person p1=new Person();
p1.talk();
Person p2=new Person();
p2.talk();
}
}
Another way of initialize the instance variables by using
constructor

Constructors:
Constructors are useful to initialize the instance variables.
Constructor name and class name must be same. Constructor
are not returning anything not even void. There are two types
of constructors
1. Default constructor
2. Parameterized Constructor
If you are not specifying any constructor compiler add a default
constructor to your code. If youre not specifying any input
parameters. That constructor is called default constructor.

If you are passing any input parameters to the constructor that


is called parameterized constructor.
Ex:
public class Person {
private String name;
private int age;
public Person() {
name="srinu";
age=12;
}
public Person(String name1,int age1) {
name=name1;
age=age1;
}
void talk(){
System.out.println("my name is"+name);
System.out.println("my age is"+age);
}
}

public class Demo {


public static void main(String[] args) {
Person p1=new Person();
p1.talk();
Person p2=new Person("ravi",25);
p2.talk();
}

}
O/P:
my
my
my
my

name issrinu
age is12
name isravi
age is25

Suppose if you are taking constructor input parameter name


and instance variables name are same by the time we have to
use this keyward.
public class Person {
private String name;
private int age;
public Person(String name,int age) {
this.name=name;
this.age=age;
}
}
Another way of declaring instance variables by using setters
and getters methods.
Setter Method: Its sets data to the instance variables.
Getter Method: By using this method we can get the data from
the instance variables.
Ex:
public class Person {
private String name;
private int age;
public String getName() {

return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
void talk(){
System.out.println("my name is"+name);
System.out.println("my age is"+age);
}
}

public class Demo {


public static void main(String[] args) {
Person p1=new Person();
p1.setName("Ravi");
p1.setAge(60);
p1.talk();
}
}
Types of variables:
Based on the type of values stored in the variable, All variables are
divide into two types
Primitive variables

Int x;
Reference variables
String str=new String(srinu);
Based on the purpose and position of declaration all the variables are
divide into 3 types.
Instance variables
Static variables
Local variables
Instance variables:
If the values of a variable is varied from object to object such type of
variables are called Instance variables
For every object a separate copy will be shared.
Instance variables will be created at the time of object creation and will
be destroyed at the time of object destruction i.e the scope of instance
variables is exactly same as object scope of object.
We can declare instance variables with in class but outside a method,
constructor ,or block.
If you are not initializing any thing jvm will give default values.
Static variables:
If the value of variable is fixed for all objects, then it is not recommend to
declare those variables as instance level. Such type of variables we can
declare at class level by using static keyword.
For the static a single copy will be shared the all objects.
We can declare static variables with in class but outside a method,
constructor , or block.
Static variables will be created at the time of class loading.
We can access static variables by using class name or by using object

reference.
package org.sun;
public class InstanceDemo {
inti=10;
static intj=20;
double c;
boolean ch;
public static void main(String[] args) {
InstanceDemo instanceDemo=new InstanceDemo();
instanceDemo.i=100;
instanceDemo.j=200;
System.out.println(instanceDemo.i);
System.out.println(instanceDemo.c);
System.out.println(instanceDemo.ch);
InstanceDemo instanceDemo1=newInstanceDemo();
instanceDemo1.j=300;
System.out.println(instanceDemo1.i);
System.out.println(instanceDemo1.j);
System.out.println(instanceDemo.j);
}
}

Local variables:
If you declare a variables with in a method or constructor or block such
type of variables are called local variables.
Local variables are called temporary variables or stack variables or
automatic variables.
Local variables will be created as the part of method execution. And will
be destroyed once method execution completes.
For the local variables jvm wont provide any default values. Before
using a local variables we should perform initialization explicitly

otherwise compile time error.


public class Test {
public static void main(String args[]){
int i;
System.out.println(i);
}
}
Complie time error
public class Test {
public static void main(String args[]){
int i=10;
}

System.out.println(i);

NO ERRORS.
It is not good programming practice to perform initialization in logical
blocks for local variables because they may not execute at runtime.
The only applicable modifier for local variables is final if we are using
other modifier will get compile time error.
Note: for the static and instance variables, JVM will always provide
default values .but for the local variables jvm wont provide default
values, compulsary we should perform initialization before using.
uninitialized arrays:.

int []a;

---instance level

public class Test {


int[] i;
public static void main(String args[]){
Test t=new Test();
System.out.println(t.i);==null
System.out.println(t.i[0]);=NullPointerException
}}
public class Test {
int[] i=newint[6];
public static void main(String args[]){
Test t=new Test();
System.out.println(t.i);=[I@12a1e44
System.out.println(t.i[0]);=0
}

If it is static also same output for both scenarios.


Local level:
int []a;
System.out.println(a);CE(complie time error)
System.out.println(a[0]);CE
int[] a=new int[6];
System.out.println(a);[I@12a1e44
System.out.println(a[0]);0
If we create an array all its elements are
initialized with default values even though if it is

local.

Encapsulation
Encapsulation is the mechanism where data (variables) and the
code (methods) that act on the data will bind together. For
example take a class, we write the variables and methods
inside the class. Thus, class is binding them together. So class
is an example for encapsulation.
package org.test;
public class Person {
//variables- data
private String name;
private int age;
//method
public void talk(){
System.out.println("Hello, I am"+name);
System.out.println("My age is"+age);
}
}
The variables and methods of a class are called 'members' of
the class. Generally, the variables in the class are declared by
using a keyword 'private'. This means the variables are not
directly available to any other class. The methods of a class are
declared as 'public. This means the methods can be called and
used from anywhere outside the class. To use the variables
from outside, we should take the help of methods. There is no
other way of interacting with the variables.
This means outsiders do not know what variables are declared
in a class, and what code is written in the method that is giving
result. Others can only use them and obtain the results.

Encapsulation thus protects inner implementation of the


members of the class from outside environment.
Encapsulation isolates the members of a class from the
members of another class. The reason is when objects are
created, each object shares different memory and hence there
will not be any overwriting of data. This gives an advantage to
the programmer to use the same names for the members of
two different classes. Employee and Student
int id;
String name;

Inheritance:
It creates a new class from existing class, so that new class will
acquire all the features of the existing class is called
inheritance. A good example for
Inheritance is parents producing the childrens and children are
inheriting the qualities of the parents.
Let us take a class A with some features (members i.e..
variables and methods). If we feel another class B wants almost
same features, then we can derive or create class B from A

Now all the features of A are available to B. If an object to B is


created, it contains all the members of classes A and also its
own members. Thus, the programmer can access and use all
the members of both the classes A and B. This is called
inheritance. The original class (A) is called super class and the
derived class B is called subclass or child class.
Example for Inheritance:
package org.test;
public class A {
protected int a;

protected int b;
public void method1(){
}
}
class B extends A {
private int c;
public void method2(){
}
}

Abstraction:
There may be a lot of data, a class contains and the user does
not need the entire data. The user requires only some part of
the available data. In this case, we can hide the unnecessary
data from the user and expose only that data that is of interest
to the user. This is called abstraction.
A good example for the abstraction is a car. Any car will have
some parts like engine, radiator, mechanical and electrical
equipment etc. the user of the car (driver)
Should know how to drive the car and does not require any
knowledge of these parts. For example driver is never bothered
about how the engine is designed and the internal parts of the
engine. This is why; the car manufacturers hide these parts
from the diver in a separate panel, generally at the front.
The advantage of abstraction is that every user will get his own
view of data according to his requirement and he will not get
confused with unnecessary data.

A bank clerk should see the customer details like account


number, name and balance amount in the account. He should
not permissions to see the sensitive data like staff salaries,

profits and losses of the bank,intersest amounts paid by the


bank and loan amounts to be recovered etc,. So such data can
be abstracted from the clerks view. Where bank manager is
interested to know this data, it will be provided to the manager.
Example of the abstraction.
package org.test;
public class bank {
private int accno=1234;
private String name="srinu";
private float balance=35670.00f;
private float profit=12345.567f;
private float loan=1223222;
public void dislay_to_clerk(){
System.out.println("Account no"+accno);
System.out.println("Name"+name);
System.out.println("Balance"+balance);
}
public static void main(String args[]){
bank b=new bank();
b.dislay_to_clerk();
}
}

The above code we declared Instance variables are private


means we can access these variables with in the class this
scope is limited to the class. Here we are hiding the data to
outside class.
Note:
Suppose in Person class if you create object to bank(we can
create object to bank class because it is public class)after that
if you call above instance variables it gives compile time error.
package org.test;
public class bank {

public
public
public
public
public

int accno=1234;
String name="srinu";
float balance=35670.00f;
float profit=12345.567f;
float loan=1223222;

public void dislay_to_clerk(){


System.out.println("Account no"+accno);
System.out.println("Name"+name);
System.out.println("Balance"+balance);
}
}
In below class I can access the instance variables. Because
these variables are public.
Note: Public access specifiers we can access outside class and
outside the package(org.test1) also.
package org.test;
public class Demo {
public static void main(String[] args) {
bank b=new bank();
b.accno=911010034;
b.balance=500000.00f;
b.loan=12345;
b.name="ravi";
b.profit=200000.00f;
}
}
Here I declared instance variables are default(if we are not
writing using any access specifier complier adds default access
speifier).
In below code I declared instance variables are defult

package org.test;
public class bank {
/* Below we are declaring the instance variables not using any
private or public. compiler adds default access specifier */
int accno=1234;
String name="srinu";
float balance=35670.00f;
float profit=12345.567f;
float loan=1223222;
public void dislay_to_clerk(){
System.out.println("Account no"+accno);
System.out.println("Name"+name);
System.out.println("Balance"+balance);
}
}
package org.test;
public class Demo {
public static void main(String[] args) {
bank b=new bank();
b.accno=911010034;
b.balance=500000.00f;
b.loan=12345;
b.name="ravi";
b.profit=200000.00f;
}
}
Note: default access specifiers we can access outside class and
within the package(org.test) also. if we access outside package
it will give compile time error.
Below code Declared variables as protected
package org.test;
public class bank {

protected
protected
protected
protected
protected

int accno=1234;
String name="srinu";
float balance=35670.00f;
float profit=12345.567f;
float loan=1223222;

public void dislay_to_clerk(){


System.out.println("Account no"+accno);
System.out.println("Name"+name);
System.out.println("Balance"+balance);
}
}
package org.test;
public class Demo {
public static void main(String[] args) {
bank b=new bank();
b.accno=911010034;
b.balance=500000.00f;
b.loan=12345;
b.name="ravi";
b.profit=200000.00f;
}
}
Note: protected access specifiers we can access outside class
and within the package(org.test) also.
We can access protected variables outside the package only in
child classes and we should use child class reference only i.e.
Parent class reference is not allow to access protected
members from outside package.
package org.test1;//this is different package
import org.test.bank;

public class Demo1 extends bank {


public static void main(String[] args) {
Demo1 d=new Demo1();
d.accno=1111;
d.balance=222222.00f;
d.loan=11223.67f;
d.name="nani";
d.profit=450000;
}
}
The same(private,public,protected,default) its applicable for
methods.
package org.test;
public class MethodsAccesSpecifiers {
void m1(){
System.out.println("default access specifier
method");
}
private void m2(){
System.out.println("private access specifier");
}
public void m3(){
System.out.println("public access specifier");
}
protected void m4(){
System.out.println("protected access specifier");
}
public static void main(String[] args) {
MethodsAccesSpecifiers ms=new
MethodsAccesSpecifiers();
ms.m1();
ms.m1();
ms.m1();
ms.m1();
}
}

package org.test;
public class Demo {
public static void main(String[] args) {
MethodsAccesSpecifiers ms=new MethodsAccesSpecifiers();
ms.m1();
ms.m2();//CE(complie time error)
ms.m3();
ms.m4();
}
}
Note: Private methods cant access outside the class.
package org.test1;//different package
public class Demo {
public static void main(String[] args) {
MethodsAccesSpecifiers ms=new MethodsAccesSpecifiers();
ms.m1();//CE(compile time error)
ms.m2();//CE
ms.m3();
ms.m4();//CE
}
}

Note: Private methods cant access outside the class. default


access specifier methods cant access outside the package(we
can access outside class but within the same package).
Protected access specifier methods we can access outside the
package compulsory we need to extends the class. And we
need to create the object to child class. Observe the below
code
package org.test1;
import org.test.MethodsAccesSpecifiers;
import org.test.bank;
public class Demo1 extends MethodsAccesSpecifiers {
public static void main(String[] args) {
Demo1 d=new Demo1();
d.m1();//CE default access specifier method not
possible to access outside the package

d.m2();////CE private access specifier method not


possible to access outside the package
d.m3();//public methods we can access outside the
package
d.m4();//protected methods we can access outside
the package(The Demo1 class extending
MethodsAccesSpecifiers and creating object to Demo1(child
class) then only we can access the protected methods)
}
}

Polymorphism:
The word 'Polymorphism' came from two Greek words 'poly'
meaning 'many' and 'morphos' meaning 'forms'. Thus,
polymorphism represents the ability to assume several different
forms.
Polymorphism provides flexibility in writing programs in such a
way that the programmer uses same method call to perform
different operations depending on the requirement.
Polymorphisms with methods:
package org.test;
public class Poly {
void add(int a,int b){
System.out.println("sum of two"+(a+b));
}
void add(int a,int b,int c){
System.out.println("sum of two"+(a+b+c));
}
void add(int a,float b){
System.out.println("sum of two int,float"+(a+b));
}
public static void main(String[] args) {
Poly p=new Poly();
p.add(12, 13);
p.add(12, 13.00f);
p.add(12, 13, 15);
}

}
This way of method declaration is called method overloading.
Method overloading:
Writing two or more methods in the same class in such a way
that each method has same name but with different method
signatures- is called method overloading.
Method signatures means the method name along with method
parameters
Dynamic Polymorphism:
The polymorphism exhibited at runtime is called dynamic
polymorphism. This means when a method is called, the
method call is bound to the method body at the time of running
the program, dynamically. In this case java compiler does not
know which method is called at the time of compilation. Only
Jvm knows at runtime which method is to be executed. Hence
this called dynamic polymorphism or dynamic binding
Note: The above code with method overloading is example of
dynamic polymorphism.
package org.test;
class One{
void calculate(int a,int b){
System.out.println(a+b);
}
}
class Two extends One{
void calculate(int a,int b){
System.out.println(a*b);
}
}
public class Poly1 {
public static void main(String[] args) {
Two t=new Two();
t.calculate(10, 15);

}
}
The above code is example of method overriding.
Method overriding:
Writing two or more methods in super and sub classes such
that the methods have same name and same signature.
In method overriding, the java compiler does not decide which
method is called by user, since it has to wait till an object to
subclass is created. After creating the object, JVM has to bind
the method call to an appropriate method. But the methods in
super class and sub classes have same name and same
method signatures. Then how jvm decides which method is
called?
Here, JVM calls the method depending on the class name of the
object which is used to call the method. For example, we are
calling the method by using the sub class object
t.calculate(10, 15);
so the sub class method is only executed by the jvm. In
heritance, we always create object an object to the subclass
and hence only sub class method is called. In this way, method
overriding using instance methods is an example of dynamic
polymorphism.
package org.test;
class One{
void calculate(int a,int b){
System.out.println(a+b);
}
}
class Two extends One{
void calculate(int a,int b){
System.out.println(a*b);
}
void calculate(int a,int b, int c){

System.out.println(a*b*c);
}
}
public class Poly1 {
public static void main(String[] args) {
One o=new Two();
o.calculate(10, 15);
o.calculate(10, 15,13);//CE
}
}
Note: The above code we are creating reference parent class
and creating object to sub class object by using that reference
we can call only sub class methods which are overridden we
cant call sub class specific methods.
Static polymorphism:
The polymorphism exhibited at compilation time is called static
polymorphism. Hence the java compiler knows without any
ambiguity which method is called at the time of compilation, Of
course, JVM executes the method later, but the compiler knows
and can bind the method call with method code at the
compilation. So, it is also called static binding or compile time
polymorphism.
In previous examples the method overloading and overriding
using instance methods are examples for dynamic
polymorphism.
Similarly, achieving method overloading and the method
overriding by using static methods, private methods, and the
final methods are examples for static polymorphism. The
reason all these methods are maintain only one copy in
memory that is available to the objects of the class. So the java
compiler knows which method is called at the time of
compilation and it needs not wait till the objects are created.
Since at the time of compilation, the method call can be bound
with actual method body, this comes under static
polymorphism.

Polymorphism with Static Methods


A static method is a method whose single copy in a memory is
shared by all the objects of the class. Static methods belong to
the class rather than to the objects. So they also called class
methods. Static methods can be overloaded and overridden.
Since they dont depend on the the objects, the java compiler
need not wait till the objects are created to understand which
method is called.
package org.test;
class One{
static void calculate(int a,int b){
System.out.println(a+b);
}
}
class Two extends One{
static void calculate(int a,int b){
System.out.println(a*b);
}
}
public class Poly1 {
public static void main(String[] args) {
One o=new Two();
o.calculate(10, 15);
}
}
Note: static methods cant overridden. Above code it executes
super class method.
Polymorphism with private methods
Private methods are methods which are declared by using
private access specifier makes the method not to be available
outside the class. So other programmers cannot access the
private methods. Even private methods are not available in the
subclass. This means there is no possibility to override the
private methods of the super class in its sub classes. Only
method overloading is possible in case of private methods.

What happens if a method is written in the sub class with the


same name as that of the super class? It is possible to do so.
But in this case, the method in the super class and the method
in the sub class acts as different methods. The super class will
gets own copy and the sub class will have its own copy. It does
not comes under method overriding.
Can you override private methods?
No. Private methods are not available in the sub classes, so
they cannot be overridden.
package org.test;
class One{
private void calculate(int a,int b){
System.out.println(a+b);
}
}
class Two extends One{
private void calculate(int a,int b){
System.out.println(a*b);
}
public static void main(String[] args) {
Two o=new Two();
o.calculate(10, 15);
}
}
Note: This is not a overriding the method in the super class and
the method in the sub class acts as different methods.
Polymorphism with final methods
Methods which are declared as final are called final methods.
Final methods cannot be overridden, because they are not
available to sub classes. Therefore, only method overloading is
possible.
package org.test;
class One{
final void calculate(int a,int b){
System.out.println(a+b);
}

}
class Two extends One{
final void calculate(int a,int b){
System.out.println(a*b);
}
CE(Compile time error)
Final class
A final class is a class which declared as final keyword before
the class
Note: if we declare class as final we cant extends that class
this means subclass cannot be created to a final class.
final class A
class B extends A //CE

Object oriented programming languages follows all the features


of the oop's example:java,c++,small talk,simula-67.

Object based programming languaage follows all the features


of the oop's except Inheritance. Forexample, java script and vb
script

Вам также может понравиться