Professional Documents
Culture Documents
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:
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.
}
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{
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());
}
}
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.
}
O/P:
my
my
my
my
name issrinu
age is12
name isravi
age is25
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);
}
}
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
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
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.
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
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.
public
public
public
public
public
int accno=1234;
String name="srinu";
float balance=35670.00f;
float profit=12345.567f;
float loan=1223222;
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;
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
}
}
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.
}
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