You are on page 1of 25

OOPS

class,object

class:

In object-oriented programming, a class is a programming language


construct that is used as a blueprint to create objects. This blueprint
includes attributes and methods that the created objects all share.

Usually, a class represents a person, place, or thing - it is an


abstraction of a concept within a computer program. Fundamentally, it
encapsulates the state and behavior of that which it conceptually
represents. It encapsulates state through data placeholders called
member variables; it encapsulates behavior through reusable code
called methods.

More technically, a class is a cohesive package that consists of a


particular kind of meta data. It describes the rules by which objects
behave; these objects are referred to as instances of that class. A
class has both an interface and a structure. The interface describes
how the class and its instances can be interacted with via methods,
while the structure describes how the data is partitioned into attributes
within an instance. A class may also have a representation (meta
object) at run time, which provides run time support for manipulating
the class-related meta data. In object-oriented design, a class is the
most specific type of an object in relation to a specific layer.

Programming languages that support classes all subtly differ in their


support for various class-related features. Most support various forms
of class inheritance. Many languages also support features providing
encapsulation, such as access specifiers.

class Example:

Class java

properties(variables);

Actions(methods);

}
object:

In its simplest embodiment, an object is an allocated region of


storage. Since programming languages use variables to access
objects, the terms object and variable are often used interchangeably.
However, until memory is allocated, an object does not exist.

Any language present objects and this should not be confounded with
the most powerful concept of object-orientation.

In procedural programming, an object may contain data or


instructions, but not both. (Instructions may take the form of a
procedure or function.) In object oriented programming, an object
may be associated with both the data and the instructions that operate
on that data.

How an object is created depends on the language. In aprototype-


based language (e.g.,JavaScript) an object can be created from
nothing, or can be based on an existing object. In a class-based
language (e.g- ,Java), an object is created as an instance (or
instantiation) of a class. The class forms a specification for the object.

To give a real world analogy, a house is constructed according to a


specification. Here, the specification is a blueprint that represents a
class, and the constructed house represents the object.
Object example:
class Sam

int i=10;

void mone()

System.out.println("java");

public static void main(String arg[])

{
Sam s=new Sam(); //Here is the Object

Thank you for visiting Java Examples.For regular updates request you to subscribe to my
RSS Feed or register your Email Subscription for updates directly into your mail box.

Labels: OOPS comments (0)

Abstraction

Hiding internal implementation is called Abstraction.


Advantages:
Security
Enhancement easy
we can enhance the internal implementation with out effecting outside
world.

Thank you for visiting Java Examples.For regular updates request you to subscribe to my
RSS Feed or register your Email Subscription for updates directly into your mail box.

Labels: OOPS comments (0)

Encapsulation

Encapsulation Advantages:
Security
Easy to enhance
Maintainability
Modularity
Example:
class Sample
{
public int i=10;
public int getId()
{
return i;
}
public void setId(int x)
{
this.i=x;
}
}
The major limitations od encapsulation is,it increases the code
(because we have to getter and setter methods for the data variables )
and hence slows down the execution.

Tightly encapsulated class:


A class is said to be tightly encapsulated if and only if data members
as the private
Check whether the fallowing classes are tightly encapsulated or not.
a)
class A {
private int x=10;
public void setX(int x)
{
this.x=x;
}
public int getX()
{
return x;
} ------------------//tightly encapsulated

b). class A{ private int y=10;} -----//tightly encapsulated

c). class A{ private int x=20;} ----// A is tightly encapsulated, B is not


class B extends A{ private int y=30;}

d). class A{ int y=20;}


class B extends A{ private int z=40;}
class C extends B { private int l=50; }

• If the parent class is not tightly encapsulated no child class is tightly


encapsulated.
Thank you for visiting Java Examples.For regular updates request you to subscribe to my
RSS Feed or register your Email Subscription for updates directly into your mail box.

Labels: OOPS comments (0)

Java Inheritance

IS-A relation:
• Also known as Inheritance
• By using extends keyword we can implement IS-A relationship.
• Re usability is the benefit of IS-A relationship
Inheritance is accepted up to certain level but after reaching problems.
Because for every child class object, internally all the parent objects
will be created in the inheritance tree.
In the real time it is recommended to have inheritance up to 8 to 10
levels only. Beyond that it is not suggestible.
is a relation Example:
class Superclass
{
void display()
{
System.out.println("Hi");
}
}
class InheritanceExample extends Superclass
{
public static void main(String arg[])
{
InheritanceExample ie=new InheritanceExample();
ie.display();
}
}
HAS-A relation:
• Also known as composition or Aggregation.
• By using new operator we can implement HAS-A relationship.
• Reusability(CBM->Component Based Model)is the benefit of HAS–A
relationship.
• The limitation of HAS-A relation ship is , we are increasing the
dependency between the classes. As a result, the maintenance of the
code becomes complex or costly.
has a relation Example:
class Car
{
Engine e= new Engine();
. …….
.......
}
class Engine
{
m1(){}
m2(){}
}

Car class has Engine reference. Hence Car allowed using all the
features of engine. But without Engine object we can’t create Car
object.

Thank you for visiting Java Examples.For regular updates request you to subscribe to my
RSS Feed or register your Email Subscription for updates directly into your mail box.

Labels: OOPS comments (0)

Method Signature

Method Signature :
Example:
public void m1(int a, int b)
{
m1(int,int); -----> signature of method m1
}

Example:
public void m1(int a, float b)
{
m1(int , float); //valid
m1(float , int);//invalid
}

• In java the method signature is compiled with method name and


argument list (the order of arguments also important).
• Return type is not part of the signature.
• Compiler uses the method signature to resolve method calls.
• With in a class two methods having same the signature is not
allowed, violation needs to CTE saying method is already defined in class.

Example:
class Test
{
public int m1(int i){}//invalid, CTE: m1(int) is already defined in test
public void m1(int i){}
}

Thank you for visiting Java Examples.For regular updates request you to subscribe to my
RSS Feed or register your Email Subscription for updates directly into your mail box.

Labels: OOPS comments (0)

Method Overloading

Method Overloading:
Two methods having the same name are not allowed in the case of C-
language, for every data type even though the functionality in the
same; we should maintain different method names. It increases the
complexity of the programming. But in java, two methods having the
same name is allowed irrespective of parameters. We can maintain the
same method name for similar type of functionality. It simplifies the
programming. Such types of methods are called Overloaded methods.
• Two methods are said to be overloaded if and only of they have the
same method name, but different parameter list(at least order).
• The signatures of the two overloaded methods must be different.
Example:
public void m1(){}
private int m1(int i){}
• Here m1() & m1(int i) are overloaded. We never consider return
type, access modifier and throws class in overloading.
Example:
class Sample
{
public void m1()
{
System.out.println(“no arg”);
}
public void m1(int i)
{
System.out.println(“ int arg”);
}
public void m1(double d)
{
System.out.println(“ double arg”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1();
s.m1(10);
s.m1(10.5);
}
}

• In the case of overloading which overloaded method must be


executed is decided method must be executed is decided by compiler
only based on reference type.
• Ie., Overloaded method resolution is the duty of compiler only.
Hence Overloading is the best
ex. of static polymorphism and some times also known as Early
Binding.

s.m1(10L);//double arg
s.m1(‘a’);//int arg

i.e., Automatic Promotion in Overloading:


• If we are calling a method m1() by passing char as arg on the
sample reference then the compiler will check in the Sample class for
m1(), which can take char as the arg.
• If it finds that method, it will execute at run time.If there is no such
method the compile promotes that char arg to the int arg and checks
for m1(int) method.
• If there is no such method, the compiler will check for m1(long),
fallowed by m1(float),fallowed by m1(double). Still if the compiler
won’t find any such method then only compiler will raised CTE saying
‘cannot resolve the symbol m1(char).
CASE 1:
class Sample
{
public void m1(int i,float f)
{
System.out.println(“int,float”);
}
public void m1(float i,int f)
{
System.out.println(“float,int”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1(10,10.0f);//int,float
s.m1(10.0f,10);//float,int
s.m1(10,10);//invalid-> CTE:reference m1 is ambiguous
}
}
CASE 2:
class Sample
{
public void m1(String s)
{
System.out.println(“String version”);
}

public void m1(Object o)


{
System.out.println(“Object version”);
}
public void m1(double d)
{
System.out.println(“double version”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1(“viswan”);// String version
s.m1(new Object());// Object version
s.m1(null);// String version
}
}
If there is Double (wrapper class) then CTE: reference to m1 is
ambiguous.
CASE 3:
class Animal
{
}
class Monkey extends Animal
{
}
public class OLStaticBinding {

public void m1(Animal a)


{
System.out.println("Animal version");
}
public void m1(Monkey m)
{
System.out.println("Monkey version");
}
public static void main(String a[])
{
OLStaticBinding s=new OLStaticBinding();
Animal a1 =new Animal();
s.m1(a1); // Animal version
Monkey m =new Monkey();
s.m1(m); // Monkey version
Animal a2 =new Monkey();
s.m1(a2); // Animal version

}
}
In the case of overloading the method resolution performed by the
compiler is based on the reference type.

Thank you for visiting Java Examples.For regular updates request you to subscribe to my
RSS Feed or register your Email Subscription for updates directly into your mail box.
Labels: OOPS comments (0)

Method Overriding

If you don’t want parent class implementation for any method we can
override in the child class based on our child class requirement. This
concept is called Overriding.
While overriding we have to fallow rules:
1. In the overriding, the method names and arg’s must be same.
Ie. In the case of the overriding the signatures of the methods must
be same
Until 1.4 version, the return types must be same. But from 1.5 version
onwards covariant return types are also allowed.
Example:
class p { public Number getNumber(){} }
class c extends P{ public Number getNumber(){} }

(or)
class C extends P
{
public Byte/Short/Integer getNumber(){}
}

• For Number class Byte/Short/Integer is co-variant return types


or classes.
• Hence in case of overriding as the return type we can keep child
class objects also.

Example:
import java.io.*;
class P
{
public object m1(){ return new object; }
}
class C extends P
{
public Object m1(){ return new Object; }
}
class C extends P
{
public String m1(){ return “durga”; }
}//in 1.4 CTE saying m1() in C cannot override found:string,
req:object: in 1.5 ver no CTE

2. final methods can’t be overridden.


3. private methods never participate in the in the overriding because
these methods are not visible in the child classes.
4. While overriding decreasing access specifier is not allowed. Violation
leads to CTE.

class P { public int m1(){} }


class C extends P { public int m1(){} }
Parent class -------------------------------- Child class
public ----------------------------------------------- public
protected ---------------------------------------- protected, public
default ---------------------------------------- default, protected ,public
private ---------------------------------------- private, default, protected,
public

* While implementing any interface method, we should declare that


method as public in the implemented class.(by default implements
interface method is public and abstract)
* An abstract method can be overridden as abstract. The child of the
original child class is responsible for the implementation.

class P{
public void m1()
{ } }//non abstract
abstract class C extends P{
public abstract m1(); }//valid abstract

5. While overriding the size of the CheckedException should not


increase. There is no rule for UnCheckedExceptions.
Example: Base or parent class :
public void m1()throws IOException
Derived or child class :

public void m1()throws FileNotfoundException //valid

public void m1()throws Exception -->CTE

public void m1()throws RunTimeException //valid


• We can override a synchronized method to non-synchronized
and vice versa
• We can override native to native to non native and vice versa.
• We can override a non-final method to final method.
• We can’t override a static method to non static and a non-static
method to static violation leads to CTE .
• While overriding method has to execute will be decided by JVM
based on the Run Time Object. Hence Overriding is an example
of “dynamic polymorphism” or “LateBinding” (Dynamic Method
dispatch).
• If the parent’s class reference can be used to hold child class
object by using that reference we are allowed to call only parent
class methods. Child class specific methods are not allowed to
call by using parent class reference.

Method Hiding:-
This is exactly same as overriding except both parent & child class
methods must be declared as static. In the method hiding the method
resolution take care by compiler only based on the reference type.
Ex:
class P
{
static int x=10;
int y=20;
}
class C extends P
{
static int x=100;
int y=200;
}
class Sample
{
public static void main(String[] a)
{
P p=new C();
System.out.println(p.x+”,”+p.y); //10,20
C c=new C();
System.out.println(c.x+”,”+c.y); //100,200
P p1=new P();
System.out.println(p1.x+”,”+p1.y); //10,20
}
}
• We can’t override in the child class. But if define exactly same
variable in child class.
• Variable resolutions take care by compiler only based on the
reference type.

Thank you for visiting Java Examples.For regular updates request you to subscribe to my
RSS Feed or register your Email Subscription for updates directly into your mail box.

Labels: OOPS comments (2)

Constructors

The purpose of Constructor is to perform of our creted object.


Whenever we are calling new operator for the creation of object, it
calls constructor automatically to provide initialization for the object.
class Student
{
String name; int rno;
Student(String name, int rno) ----> Constructor
{
this.name=name;
this.rno=rno;
}
public static void main(String a[])
{
Student s=new Student(“xxx”,101);
Student s1=new Student(“yyy”,102);
-------
------
}
}
Rules Of Constructor :
1. Constructor concept is applicable for every class including abstract
class also.
2. Interface doesn’t have Constructor’s concept.
3. The name of the const4ructor and the name of the class must be
same.
4. The allowed modifiers for the constructors are public, private,
protected, and default. If you are applying any other we will get a CTE
saying “modifier xxx not allowed her”.
5. We can’t give return type for the constructor even void also.

If we will give return type for the constructor that thing as a method
instead of constructor that thing as a method instead of constructor
(so,there is no CTE). Ie., it is legal (but stupid) to have a method
whose name same as classname.
Default Constructor:-
If the programmer is not writing any constructor, then only compiler
will generate a default constructor.
Ie., either programmer written constructor or compiler generated must
present in your class but not both at a time.
Prototype of default constructor shown below:
a).Programmer written code:- class Test{}
Compiler generated code:-
class Test
{
Test()
{
super();
}
}

• The default constructor is always no argument constructor.


• The access modifier of the default constructor is sane as access
modifier of the class (public & default only).
• The default constructor contains only one statement which is ‘no
arg call to super class Constructor ‘ (super();)

b) Programmer written code:-


class Test {
Test(int i)
{
System.out.println(“constructor”);
}}
Compiler generated code:-
class Test {
Test(int i)
{
super();
System.out.println(“constructor”);
}}

c). Programmer written code:-


class Test {
Test(int i)
{
super();
System.out.println(“Hai”);
}}
Compiler generated code:- no new code is going to generate.

d). Programmer written code:-


class Test {
void Test()
{
System.out.println(“hello”);
}
}
Compiler generated code:-
class Test {
void Test()
{
System.out.println(“hello”);
}
Test()
{
super();
}}
e). Programmer written code:-
class Test {
Test()
{
this(10);
System.out.println(“hai”);
}
Test(int i)
{
System.out.println(i);
}}
Compiler generated code:-
class Test {
Test() {
this(10);
System.out.println(“hai”);
}
Test(int i) {
super();
System.out.println(i);
}}

• The first line inside a constructor must be a call to super class


constructor ( by using super();) or a call to overload constructor
of the same class. (by using ‘this’ keyword).
• If you are not writing the first line as either ‘super()’ or ‘this’
then compiler will always keep a no arg call to super class
constructor (super();).

1. Allowed only in Constructors.


2. Must be first statements.
3.Either super() or this, but not both.

• We can invoke another constructor from constructor from a


method violation leads to CTE. i.e, super() or this must be used
inside the constructor only not anywhere else.

Overloaded Constructors:
We are allowed to keep more than one constructor inside a class ,
which are considered as overloaded constructors. We can’t override
the constructors, because they belong to the same Ex: class Test {
Test(int i){}
Test(){} ---->Overloaded Constructors
}

• Constructors are not inherited and hence we are not allowed to


override a constructor.
• while recursive method invocation we will get
stackoverflowException But in case of constructors we will get
compile time error.
• If we are writing any constructor in our class it is recommended
to place default constructor also. Otherwise we should take care
while writing the constructor child case.
• If the parent class constructor throws some Checked Exception,
while writing child class constructors we should take care.In case
of unchecked exception no rule.

Recursive Constructor invocation:


class Sample {
Sample() // This is a compile time problem
{
this(10);
}
Sample(int i)
{
this(); // Invalid, CTE: recursive constructor invocation
}
public static void main(String a[])
{
System.out.println(“hai”);
}
}
Constructing the Child class constructors:
Example:
class P {
P()
{ super(); }
}
class C extends P
{
C() {
super();
} } //valid

Example:
class P {
P(int i)
{
System.out.println(i);
}
}
class C extends P
{
C()
{
super(10); // valid (without super invalid)
}
}

Example: class P
{
P() throws Exception ----> checked exception
{}
}
class C extends P
{
C() // compile time error unhandled exception type exception
{}
}

Thank you for visiting Java Examples.For regular updates request you to subscribe to my
RSS Feed or register your Email Subscription for updates directly into your mail box.

Labels: Constructors, OOPS comments (0)

Saturday, February 7, 2009


abstract class

We can apply abstract keyword for the classes and methods .abstract
keyword is not possible for variables.If method declared as abstract we
don’t know implementation child class is responsible to provide the
implementation for the parent class abstract methods.

Abstract public void m1(); // here ; is mandatory.

Abstract method has declaration only and should not have any
implementation.
This is the way of decorating abstract method .we should not keep
curly braces at end.

• If a class contain at least one abstract method we should have to


declare that class as abstract other wise compile time error.

• An abstract class is not compulsory to have an abstract


method.i.e abstract class may contain zero number of abstract
methods also.this is for restricting object creation.

• HttpServlet class doesn’t contain any abstract methods ,still the


class is declared as abstract because the methods present in
HttpServlet can’t provide any request ,response for the end
user ,these methods are just for sending error information.
• It’s a good programming practice to use abstract methods
,abstract classes and interfaces.
Example:
class Sam
{
abstract void m1(); //error
}

Example 2:
abstract class Xy
{
abstract void m1(); // valid
}

Example 3:
abstract class X
{
void m1() // valid
{
System.out.println(“valid”);
}
}

Example 4:
abstract class X
{
abstract void m2();
}

class Y extends X // error we must provide the implementation for m2


method .
{
}

Abstract class examples

1.Abstract class with constructor.

Thank you for visiting Java Examples.For regular updates request you to subscribe to my
RSS Feed or register your Email Subscription for updates directly into your mail box.

Labels: Fundamentals, OOPS comments (0)


interface

An interface defines the contract between service provider and the


client without highlighting internal implementation.
i.e Interface describes the services ,what service provider provides and
what client get.
The main advantage of interface are :
1. we never high lite our implementation to the outside world,we can
achieve security for our implementation.
2. With out effecting outside world,we can enhance our internal
implementation. Interface is considered as 100% pure abstract class
because we never keep implementation inside interface. And hence all
the methods present inside an interface are abstract methods.
For the service provider point of view an interface defines the services
provided by that person.
From the client point of view an interface describes what services he
required.

Declaring an interface:
interface Interf
{
public void m1();
public void m2();
}
class Bea implements Interf
{
public void m1()
{
System.out.println(“implementation m1”);
}
public void m2()
{
System.out.println(“implementation m2”);
}
public static void main(String arg[])
{
Interf i=new Interf();
i.m1();
}
}

• If you want to provide implementation for any interface


method ,it must be declared as public .
• The first concrete class which implements an interface must
provide implementation for all the interface methods other wise
the class must declared as abstract.
• We can declare an interface (top level) with <default> and
public,abstract,strictfp modifiers.

interface methods Declarations:


All the interface methods by default abstract and public (either we are
specify or not specify) not concrete method.
Examples:
Void m1();
public void m1();
abstract void m1();
public abstract void m1();
All the above are same .
Hence the above four methods declaration are identical.
An interface method never be declared as native ,strictfp,private
,static, synchronized and protected.

interface variables Declarations:


All the interface variable are by default public ,static and final.
Hence the following variable declaration inside an interface are
identical.

interface interf
{
int x=10;
public int x=10;
public static final int x=10;
final int x=10;
static int x=0;
}
Hence an interface we never declared as private ,protected and
transient.

All the interface variables must perform initialization at the time of


declaration.
Hence the following code will not compile.

interface Interf
{
int x;
}
Inside implement classes we are not allowed to change the value of
interface variable violation leads to compile time error.
Class Sample implement Interf
{
public static void main(String arg[])
{
x=20; //compile time error
}
}
A class can extend only one class at a time .But can interface can
extend any number interfaces.
A class can implement any number of interfaces at a time.But interface
never implement another interface.

Naming conflicts inside interface:


Case 1:
interface Left
{
public void m1();
}
interface Right
{
public void m1();
}
class Central implement Left,Right
{
public static void main(String arg[])
{
public void m1()
{
}
}
If two interfaces have the two are more same methods ,then only one
method implementation is enough from both interfaces.

Case 2:
The interface having same method name but different arguments.
Interface Inter
{
public void m1();
public void m1(int x);
}

case 3:
Same method name,same arguments but different written types.
Interface Left
{
public void m1();
}
Interface Right
{
public int m1();
}

class Central implement Left,Right


{
public static void main(String arg[])
{
public void m1() // error
{
}
public int m1() // error
{
}
}
}
In the above class same method signature m1 is not allow .violation
leads to compile time error.

Exceptional case :
We can’t provide implementation at a time for two or more interfaces
having methods with same signature but different return type .

Variable Naming conflicts:


interface Left
{
int x=10;
}
interface Right
{
int x=100;
}
class Central implement Left,Right
{
public static void Main(String arg[]
)
{
System.out.println(x); // reference to x is ambiguous both variables
System.out.println(Right.x);
System.out.println(Left.x);
}
}
we can resolve variable naming conflicts using interface name.(i.e
instead of x we have to specify left.x or right.x).

Tag Interface Marker/Ability Interface:


If an interface is marked for some ability such type of interfaces are
called maker interfaces or tag interface or ability interface.
Example: Comparable,Serializable,Clonable
If an interface doesn’t contain any method ,it is usually marker
interface.Even though interface contains some methods still we can
use the term marker interface if this interface is marked for some
ability.
Example: Comparable(contains method compareTo())
Adapter classes doesn’t contain concrete methods ,contain only empty
implementation of the methods.

Difference between abstract class and interface:


Interfaces provides more security and high performance when
compare to abstract classes.
Abstract class may contain concrete methods but an interface never
contain any concrete method.

You might also like