Sunteți pe pagina 1din 61

Object Oriented Programming Tutorial

DMA vs SMA
Dynamic memory allocation is runtime
Static memory allocation is compile time
Object Oriented Programming
Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology to design a program using classes and objects. Its main
concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Primitive
Primitive data type
Int, float , double Boolean, string…..
Explicitly
Anything create by customize call is explicitly.
Change the type of variable customlly is call explicitly.
Change the type of variable on runtime is call explicitly.
Implicitly
Anything create by default call is implicitly.
Change the type of variable by customlly
Change the type of variable on compile time is call explicitly.

Instance
Any thing belongs to object is instance
An instance is a specific representation of an object,
an instance is a single object that has been created in memory.
Instances have attribute and behaviors of class
Instance:
Student s1=new student ("Martin"); Student s2=new student ("Kumar");
s1 and s2 are instances of object student the two are unique.
it can be called as reference also.
Basically the s1 and s2 are variables that are assigned an object

All the objects are instances. All the instances may not be objects. Instances may be
"structure instances" or "objects".

worldclock
Object Oriented Programming Tutorial

Instance

The instance of operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).

The instance of in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instance of operator with
any variable that has null value, it returns false

Instantiating
any thing point to object is call instantiating
B =new class ()// its call instantiating
an instance (chair 3) is a single unique, specific representation of an object (a chair).
Member
Members are just objects or primitive types belonging to a class
The following table provides an overview of the kinds of members a class can contain.
(Rows for...)
 Constants

 Fields
 Methods
 Properties
 Indexers
 Events
 Operators
 Constructors
 Destructors
 Types
Property
 A property describes some aspect of the object
 Properties are a way to expose fields, where fields are the actual variables
 Class member variables are called "properties
 Variables in the class is call property
Instance variable
A variable that is created inside the class but outside the method is known as instance
variable. Instance variable doesn't get memory at compile time. It gets memory at runtime
when object (instance) is created. That is why, it is known as instance variable.

current local time


Object Oriented Programming Tutorial

Instance member variable


Create a variable without static keyword is call instance member variable
Instance member method
Create a method without static keyword is call instance member method
Static member variable or class member variable
Create a variable with static keyword is call class member or static member variable
Static member method or class member method
Create a method with static keyword is call class member or static member method
Object An entity that has state and behavior is known as an object e.g. chair, bike,
marker, pen, table, car etc. It can be physical or logical (tangible and intangible). The
example of intangible object is banking system.

An object has three characteristics:

 State: represents data (value) of an object.


 Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
 Identity: Object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. But, it is used internally by the JVM to identify
each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects


are created. So object is the instance (result) of a class.

Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.
Object is a thing, but instance is a part of a bundle thing. For example, if Car is a class, then
it should contain some of the objects like wheel, steering, door and seat. Now lets come to
the point: an object (wheel) is an instance of the Car
Memory allocated for the member of class at run time is called object or object is the
instance of Class.
Object - An instance of a class that has its own state and access to all of the behaviour
defined by its class.

Object s are instances of class


Object is complex data structure
Attribute and behaviors
Student s1=new student ("Martin"); Student s2=new student("Kumar");
The s1, s2 are having object of class Student

time zone
Object Oriented Programming Tutorial

Anonymous object
Anonymous simply means nameless. An object that has no reference is known as
anonymous object.

If you have to use an object only once, anonymous object is a good approach.

Class
A class is a group of objects that has common properties. It is a template or blueprint
from which objects are created.

A class in java can contain:

 data member
 method
 constructor
 block
 class and interface

Difference between object and class


There are many differences between object and class. A list of differences between object
and class are given below:

No. Object Class

1) Object is an instance of a class. Class is a blueprint or


template from which objects
are created.

2) Object is a real world entity such as pen, laptop, Class is a group of similar
mobile, bed, keyboard, mouse, chair etc. objects.

3) Object is a physical entity. Class is a logical entity.

4) Object is created through new keyword mainly Class is declared using class
e.g. keyword e.g.
Object Oriented Programming Tutorial

Student s1=new Student(); class Student{}

5) Object is created many times as per requirement. Class is declared once.

6) Object allocates memory when it is created. Class doesn't allocated


memory when it is
created.

7) There are many ways to create object in java There is only one way to
such as new keyword, new Instance() method, define class in java using
clone() method, factory method and class keyword.
deserialization.

Aggregation
If a class has an entity reference, it is known as Aggregation. Aggregation represents HAS-A
relationship.

Consider a situation, Employee object contains many information’s such as id, name, email
ID etc. It contains one more object named address, which contains its own information’s
such as city, state, country, zip code etc

Why use Aggregation?


 For Code Reusability.

When use Aggregation?


 Code reuse is also best achieved by aggregation when there is no is-a relationship.
 Inheritance should be used only if the relationship is-a is maintained throughout the
lifetime of the objects involved; otherwise, aggregation is the best choice.

New keyword
The new keyword is used to allocate memory at runtime.

time change
Object Oriented Programming Tutorial
Static keyword

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

The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class

Static mean method and property access without Creating object.


Static does not belong to object but belong to class
Static property
Static property In different name and parameter can hide the property of superclass its call overridden;
In Static term cannot have concept of overriding but have overriding concept
Access way use class name double colon:: and property
Mostly use for database connection and services.
Static property is not bound of object
Static property is changeable
Static property access in same class method use self:: and other classes use class name::and then
property name
:: this sign is call scope resolution operator

Static Members
A non-static class can contain static methods, fields, properties, or events. The static member is callable on
a class even when no instance of the class has been created. The static member is always accessed by the
class name, not the instance name. Only one copy of a static member exists. Static methods and
properties cannot access non-static fields and events in their containing type, and they cannot access an
instance variable of any object unless it is explicitly passed in a method parameter.
It is more typical to declare a non-static class with some static members, than to declare an entire class as
static. Two common uses of static fields are to keep a count of the number of objects that have been
instantiated, or to store a value that must be shared among all instances.
Static methods can be overloaded but not overridden, because they belong to the class, and not to any
instance of the class.

time difference
Object Oriented Programming Tutorial

Although a field cannot be declared as static const, a const field is essentially static in its behavior. It
belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the
same ClassName. MemberName notation that is used for static fields. No object instance is required.

Static Block
Static block is mostly used for changing the default values of static variables. This block gets
executed when the class is loaded in the memory.
A class can have multiple Static blocks, which will execute in the same sequence in which
they have been written into the program.

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

 The static variable can be used to refer the common property of all objects (that is
not unique for each object) e.g. company name of employees, college name of
students etc.
 The static variable gets memory only once in class area at the time of class loading.

 Static variables are also known as Class Variables.


 Such variables get default values based on the data type.
 Data stored in static variables is common for all the objects ( or instances ) of that
Class.
 Memory allocation for such variables only happens once when the class is loaded in the
memory.
 These variables can be accessed in any other class using class name.
 Unlike non-static variables, such variables can be accessed directly in static and non-
static methods.

Static local variable


In function we create a static variable is static local variable
Simple variably function call reputedly but static variable call once

watch time in qlocktwo


Object Oriented Programming Tutorial

Static global or member variable


In class we create a static variable and access it any static method is call static global variable
In class create a variable with static keyword is call static member is call static member variable
and also known as class member variable created only once time in class;
Private static member variable cannot access outside the class
If want to access a private instance then create a public method in same class then assign the
static variable to this method then access the private class
static member method/function
Any method which static keyword is call static member method
static member method created when we don’t need object in the class then we create static
member function
Static functions and variable are used to access Variables/functions in a global scope,
When something is static, it can be accessed anywhere, and is very similar to a procedural
type function
Static method in different name and parameter can extend;
In Static term cannot have concept of overriding but have overhand concept
Access way use double colon::
Mostly use for database connection and services.

In static method only get static property


Static property is not bound of object
Static method access in same class use self-keyword and this sign :: and use class name::
:: this sign is call scope resolution operator

Static Methods
Static Methods can access class variables without using object of the class. It can
access non-static methods and non-static variables by using objects. Static methods
can be accessed directly in static and non-static methods.

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

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


o A static method can be invoked without the need for creating an instance of a class.
o static method can access static data member and can change the value of it.

personal world clock


Object Oriented Programming Tutorial

Restrictions for static method


There are two main restrictions for the static method. They are:

1. The static method cannot use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.

Static Class
Collection of objects is called class. It is a logical entity.
A Class can be made static only if it is a nested Class. The nested static class can be accessed without
having an object of outer class.
Static Classes and Static Members Class
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be
instantiated. In other words, you cannot use the new keyword to create a variable of the class type.
Because there is no instance variable, you access the members of a static class by using the class name
itself.
Creating a static class is therefore basically the same as creating a class that contains only static members
and a private constructor. A private constructor prevents the class from being instantiated. The advantage
of using a static class is that the compiler can check to make sure that no instance members are
accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class
except Object. Static classes cannot contain an instance constructor; however, they can contain a static
constructor. Non-static classes should also define a static constructor if the class contains static members
that require non-trivial initialization

Static vs non static

Memory is allocated for these variable Memory is allocated for these variable at the time
2
whenever an object is created of loading of the class.

Memory is allocated multiple time Memory is allocated for these variable only once
3
whenever a new object is created. in the program.

Non-static variable also known as


Memory is allocated at the time of loading of class
4 instance variable while because memory
so that these are also known as class variable.
is allocated whenever instance is created.

Static variable are common for every object that


Non-static variable are specific to an
5 means there memory location can be sharable by
object
every object reference or same class.
Object Oriented Programming Tutorial

Non-static variable can access with object


Static variable can access with class reference.
reference.
Syntax
Syntax
6

class_name.variable_name
obj_ref.variable_name

Final keyword
Final Variable if final variable assign one time value then final variable cannot change the
value and assign value by three way
i during deceleration
ii assign value by block {}
iii assign value by constructer
Final Class final class cannot extend
Final method final method cannot override

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

1. Variable If you make any variable as final, you cannot change the value of final
variable (It will be constant).
2. Method If you make any class as final, you cannot override it.
3. Class If you make any class as final, you cannot extend it.

The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of final
keyword.

time converter
Object Oriented Programming Tutorial

Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it

What is blank or uninitialized final variable?

A final variable that is not initialized at the time of declaration is known as blank final
variable.

If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an employee

Can we initialize blank final variable?

Yes, but only in constructor

Static blank final variable

A static final variable that is not initialized at the time of declaration is known as static blank
final variable. It can be initialized only in static block.

What is final parameter?

If you declare any parameter as final, you cannot change the value of it.

Can we declare a constructor final?

No, because constructor is never inherited.

This Keyword

There can be a lot of usage of java this keyword. In java, this is areference
variable that refers to the current object.

military time zone


Object Oriented Programming Tutorial

Usage of java this keyword


This keyword is reference variable contain reference (address) of other variable and represent
the caller object this make on call function and destroy on stop function

Here is given the usage of this keyword.

1. This keyword can be used to refer current class instance variable.


2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance
7. If there is ambiguity between the instance variable and parameter, this keyword resolves the
problem of ambiguity.
8. In event handling (or) in a situation where we have to provide reference of a class to
another one
9. We can pass the keyword in the constructor also. It is useful if we have to use one
object in multiple classes

Where this keyword is not required


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

this() can be used to invoked current class constructor.

The this () constructor call can be used to invoke the current class constructor (constructor
chaining). This approach is better if you have many constructors in the class and want to
reuse that constructor.

Where to use this () constructor call?


The this () constructor call should be used to reuse the constructor in the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's
see the example given below that displays the actual use of this keyword.

time zones abbreviation


Object Oriented Programming Tutorial

The keyword can be used to invoke current class method


(implicitly).
You may invoke the method of the current class by using the this keyword. If you don't
use the this keyword, compiler automatically adds this keyword while invoking the
method

This keyword can be passed as an argument in the method.


The keyword can also be passed as an argument in the method. It is mainly used in the
event handling

The keyword can be used to return current class instance.


We can return the keyword as an statement from the method. In such case, return type
of the method must be the class type (non-primitive)

Supper keyword
Super keyword is reference variable of parent class;
Call the overridden method by supper keyword
Mostly use in overridden
Call the super class property method then use super keyword
It is use for avoid naming conflict

The super keyword in java is a reference variable that is used to refer immediate parent
class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.

daylight saving time


Object Oriented Programming Tutorial

Usage of java super Keyword


1. Super is used to refer immediate parent class instance variable.
2. super () is used to invoke immediate parent class constructor.
3. Super is used to invoke immediate parent class method.

Super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used in
case subclass contains the same method as parent class as in the example given below:

Super keyword is not required


In case there is no method in subclass as parent, there is no need to use super. In the
example given below message () method is invoked from Student class but Student class
does not have message () method, so you can directly call message() method.
Access specifier and Access modifier
Access specifier
They specify where a variable can be accessed from.
Access specifier determines the visibility for a certain field / method.
The access specifier determines how accessible the field
There are 4 types of access specifiers
By using access specifier we define that who one can access our class/method and variable
(or whatever with that we use access specifier ).

Public ,Private, Protected, Default


The public and private are known as access specifiers because they specify the access.
1. public:- Visible to the world,
2. private:- Visible to the class only,
3. protected:- Visible to the package and all subclasses, and
4. default:- Visible to the package
Default
If we not define access modifier with any instance that is call default modifier
Public
Public instance access any where
Protected
Protected instance access in same and child access
Private
Private instance access only same class body
If want to access a private instance then create a public method in same class then assign the
static variable to this method then access the private class

time zones news


Object Oriented Programming Tutorial

Access Modifiers::
Access specifier determines the visibility for a certain field / method.
They specify how variables should (or should not) be accessed;
Final or volatile and/or static and/or transient.
But access modifier are properties of a class/method/variable. Access modifier is five types

1. final:- for finalizing the implementations of classes, methods, and variables


2. static:- for creating class methods and variables
3. Synchronization and volatile modifiers:- which are used for threads
4. abstract:- for creating abstract classes and methods
5. transient
Overbidding
In parent class and child class have (static) method in same name and same parameter with
same static keyword that is call over hiding

Overriding
Method Overriding is when a method defined in a superclass or interface is re-defined by
one of its subclasses, thus modifying/replacing the behavior the superclass provides. The
decision to call an implementation or another is dynamically taken at runtime, depending on
the object the operation is called from. Notice the signature of the method remains the same
when overriding.

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 subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.

Changing the behavior of method is overriding.


Overriding use for same method name and parameter if we apply different logic
If we cannot apply overriding then call both method parent and child class method car
Parent class
Function car(int c, int b){
Return gair=a+b;
}
Child class
Function car(int c,int b){
Return gair=a*b;
}

meeting planner
Object Oriented Programming Tutorial

Usage of Java Method Overriding


o Method overriding is used to provide specific implementation of a method that is
already provided by its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. Method must have same parameter as in the parent class.
3. Must be IS-A relationship (inheritance).

Can we override static method?

No, static method cannot be overridden. It can be proved by runtime polymorphism

Why we cannot override static method?

because static method is bound with class whereas instance method is bound with object.
Static belongs to class area and instance belongs to heap area.

Method Overloading in Java


1. Different ways to overload the method
2. By changing the no. of arguments
3. By changing the data type
4. Why method overloading is not possible by changing the return type
5. Can we overload the main method
6. method overloading with Type Promotion

If a class have multiple methods by same name but different parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs. So, we
perform method overloading to figure out the program quickly.
Object Oriented Programming Tutorial

Advantage of method overloading?

Method overloading increases the readability of the program.

Different ways to overload the method


There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Why Method Overloading is not possible by changing the return type of method?

In java, method overloading is not possible by changing the return type of the method
because there may occur ambiguity. Let's see how ambiguity may occur:

Can we overload main() method?

Yes, by method overloading. You can have any number of main methods in a class by
method overloading.

Function Overloading
Function overloading gives you the ability to have more than one version of a
function so that it can behave differently according to the context in which and how
it is called.
Operator overloading
When different operations are performed using the same operator, then it is called operator
overloading.
Operator overloading is a programming language features that allows operators to act differently
depending on the type of data they are operating on
Operators as member functions
Aside from the operators which must be members, operators may be overloaded as member or non-
member functions. The choice of whether or not to overload as a member is up to the programmer.
Operators are generally overloaded as members when they:

1. change the left-hand operand, or


2. require direct access to the non-public parts of an object.

how to dail international call


Object Oriented Programming Tutorial

When an operator is defined as a member, the number of explicit parameters is reduced by one, as
the calling object is implicitly supplied as an operand. Thus, binary operators take one explicit
parameter and unary operators none. In the case of binary operators, the left hand operand is the
calling object, and no type coercion will be done upon it. This is in contrast to non-member
operators, where the left hand operand may be coerced.

Difference between method overloading and


method overriding in java
1. Overloading happens at compile-time while Overriding happens at runtime: The
binding of overloaded method call to its definition has happens at compile-time
however binding of overridden method call to its definition happens at runtime.
2. Static methods can be overloaded which means a class can have more than one static
method of same name. Static methods cannot be overridden, even if you declare a
same static method in child class it has nothing to do with the same method of parent
class.
3. The most basic difference is that overloading is being done in the same class while for
overriding base and child classes are required. Overriding is all about giving a specific
implementation to the inherited method of parent class.
4. Static binding is being used for overloaded methods and dynamic binding is being used
for overridden/overriding methods.
5. Performance: Overloading gives better performance compared to overriding. The
reason is that the binding of overridden methods is being done at runtime.
6. Private and final methods can be overloaded but they cannot be overridden. It means a
class can have more than one private/final methods of same name but a child class
cannot override the private/final methods of their base class.
7. Return type of method does not matter in case of method overloading; it can be same
or different. However in case of method overriding the overriding method can have
more specific return type .
8. Argument list should be different while doing method overloading. Argument list should
be same in method Overriding.
Object Oriented Programming Tutorial

There are many differences between method overloading and method overriding in java. A
list of differences between method overloading and method overriding are given below:

No. Method Overloading Method Overriding

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


readability of the program. 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 must be In case of method


different. overriding, parameter must be same.

4) Method overloading is the example of compile time Method overriding is the example
polymorphism. of run time polymorphism.

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


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

CONSTRUCTOR
 A constructor is a special method that is used to initialize a newly created object and is called just after the memory
is allocated for the object.
 It is not mandatory for the programmer to write a constructor for the class. If no user defined constructor is provided
for a class, compiler initializes member variables to its default values.
 Numeric data types are set to 0 .
 char data types are set to null character(\0)
 reference variables are set to null
Object Oriented Programming Tutorial

 In order to create a Constructor observe the following rules


1) It has the same name as the class
2) It should not return a value not even void
Constructer is instance member function it call automatically when call the class instance
Constructor use for initialization of instance
Object of any class make object by Constructor
In class we make no constructer then compiler create two constructer copy and default constructor
If we create own any constructer then default and copy constructor cannot create by constructer
If we create any constructer then compiler creates copy constructer
Constructor is a member function function of class
The name of constructer same as the name of class;
Constructer cannot have return type
Constructer cannot a static because it is instance member function
Constructer call first on execution on program
Super class constructer call in subclass constructer by super keyword
In subclass have parameterize constructer must have super class constructer parameterize
Constructor type
Constructer has three type
i Default Constructor
Constructor has no parameter
Complier created by default which body has no code
ii Parameterize Constructor
Constructor have parameter
iv Constructor Copy
Copy constructor Complier created by default when we initialize object of same class then call
copy constructer must be object have reference type &
iii Constructor overloading

Constructor in java is a special type of method that is used to initialize the object.

Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

currency exchange rate


Object Oriented Programming Tutorial

Purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on
the type.

Parameterized constructor
A constructor that has parameters is known as parameterized constructor.

Why use parameterized constructor?


Parameterized constructor is used to provide different values to the distinct objects.

Difference between constructor and method in java


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

Java Constructor Java Method

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


object. behaviour of an object.

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

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if Method is not provided by


you don't have any constructor. compiler in any case.

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

currency converter
Object Oriented Programming Tutorial

Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to another
like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

 By constructor
 By assigning the values of one object into another
 By clone() method of Object class

Does constructor return any value?

Ans:yes, that is current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling method etc. You can perform any
operation in the constructor as you perform in the method.

Constructer Channing
Constructor call on same class Constructor is call Constructor Channing;
In same place cannot contain use super Constructor and sub Constructor
A class { __construct(){}}
b class{
__construct a (){ this->__construct()}
__construct t b (){
// first call Super construct
// then b construct
//and then a construct
}
 Constructor chaining occurs through the use of inheritance. A subclass constructor
method's first task is to call its super class' constructor method. This ensures that the
creation of the subclass object starts with the initialization of the classes above it in the
inheritance chain.
 there could be any number of classes in an inheritance chain.

 every constructor method will call up the chain until the class at the top has been
reached and initialized. Then each subsequent class below is initialized as the chain
winds back down to the orignal subclass. This process is called constructor chaining.
Object Oriented Programming Tutorial

 Use this() to call another constructor in the same class.

 super () to call another constructor in the super class

 In case we want to call another constructor, this()/super() should be the first line in the
constructor.

CONSTRUCTOR OVERLOADING

Overloading a constructor means typing in multiple versions of the constructor, each
having a different argument list, like the following examples:

1
class Car
2
{
3 Car()

4 {

6 }

7 Car(String s)

{
8

9
}
10
}
11

holidays and observances


Object Oriented Programming Tutorial

 The preceding Car class has two overloaded constructors, one that takes a string, and
one with no arguments. Because there's no code in the no-arg version, it's actually
identical to the default constructor the compiler supplies, but remember-since there's
already a constructor in this class (the one that takes a string), the compiler won't
supply a default constructor. If you want a no-arg constructor to overload the with-args
version you already have, you're going to have to type it yourself, just as in the Car
example.

 Overloading a constructor is typically used to provide alternate ways for clients to


instantiate objects of your class. For example, if a client knows the Car name, they can
pass that to a Car constructor that takes a string. But if they don't know the name, the
client can call the no-arg constructor and that constructor can supply a default name.
Important points related to Constructor overloading:

1. Constructor overloading is similar to method overloading in Java.

2. You can call overloaded constructor by using this() keyword in Java.

3. Overloaded constructor must be called from another constructor only.

4. Make sure you add no argument default constructor because once compiler will not
add if you have added any constructor in Java.

5. If an overloaded constructor called, it must be first statement of constructor in java.

6. Its best practice to have one primary constructor and let overloaded constructor calls
that. this way your initialization code will be centralized and easier to test and maintain.

Destructor
Destructor make for destroy the resources of object
Destructor automatically call when class object is destroy
Destructor is call just before when object going to destroy
Destructor is a instance member function of class
Name of Destructor is same as the name of class
Destructor can never be static
Destructor has no return type
Destructor takes on argument therefore no overloading is possible
Destructor use for destroy the resources before the object destroying

on this day in history


Object Oriented Programming Tutorial
Class a{
__destructor{ first destructor destroy the resources then destroy object}

Obj j=new b();


//resource
}
Constructor and Destructor inheritance
Constructor inheritance
When child class object call then Child class constructor calls the parent class constructor
In inheritance first call the constructor of child class then call parent class and execute the parent class
constructor first then child class
If parent class have parameterize constructer then we create constructer in child class must then child
class constructor call the parent class constructor and pass the necessary parameter
Destructor inheritance
When child class object going to destroy then child class Destructor call and execute the child class
constructor coding then call the parent class constructor call and execute
If we not created own destructor then complier create own destructor both parent and child class;
If we create own destructor in child class but not create won destructor in parent class the complier
create default destructor in parent class
Binding
Connecting a method call to the method body is known as binding.

There are two types of binding

1. Static binding (also known as early binding).


2. Dynamic binding (also known as late binding).

Early (or static) binding


All the static, private and final methods have always been bonded at compile-time
Anything that is decided by compiler while compiling can be refer to EARLY/COMPILE
TIME Binding and anything that is to be decided at RUNTIME is
called LATE/RUNTIME binding.
For Example,

Method Overloading and Method Overriding.


1) In Method Overloading your method calls to the methods are decided by the compiler in
the sense that which function is going to be called is decided by your compiler at compile
time. Hence being EARLY BINDING.
2) In method overriding, it is decided at RUNTIME which method is going to be called. So it
is referred as LATE BINDING.
Early binding refers to events that occur at compile time. early binding occurs when all
information needed to call a function is known at compile time
Late binding, or dynamic binding, is a computer programming mechanism in which the
method being called upon an object is looked up by name at runtime
Object Oriented Programming Tutorial

1. Static binding happens at compile-time while dynamic binding happens at


runtime.
2. Binding of private, static and final methods always happen at compile time since
these methods cannot be overridden. Binding of overridden methods happen at
runtime.
3. Java uses static binding for overloaded methods and dynamic binding for
overridden methods.

What is virtual function?


Virtual function is the member function of a class that can be overridden in its derived class.
It is declared with virtual keyword. Virtual function call is resolved at run-time (dynamic
binding) whereas the non-virtual member functions are resolved at compile time (static
binding).
Virtual Function will have a body and may or may not be overridden by child classes
With "virtual" you get "late binding". Which implementation of the method is used gets
decided at run time based on the type of the pointed-to object - what it was originally
constructed as. This is not necessarily what you'd think based on the type of the pointer that
points to that object.

You can create abstract functions, but you need to declare the parent class as abstract, too:

abstract class Parent {


// no implementation given
abstract public function foo();
}

class Child extends Parent {


public function foo() {
// implementation of foo goes here
}
}

A virtual function can be overridden in a derived class.

A pure virtual function must be overridden in a derived class.

A class with pure virtual functions cannot be instantiated.

united nations days


Object Oriented Programming Tutorial

1. It can be declared inside abstract as well as non abstract class.


2. It contains method implementation.
3. It may be overridden
4. An abstract method is a method that must be implemented to make a concrete class.
The declaration is in the abstract class (and any class with an abstract method must
be an abstract class) and it must be implemented in a concrete class.
5. A virtual method is a method that can be overridden in a derived class using the
override, replacing the behavior in the superclass. If you don't override, you get the
original behavior. If you do, you always get the new behavior. This opposed to not
virtual methods, that cannot be overridden but can hide the original method
6. Basically, you would use a virtual method if you have the 'default' implementation of
it and want to allow descendants to change its behavior.
7. With an abstract method, you force descendants to provide an implementation.

When you have a function in the base class, you can Redefine or Override it in the derived
class.
Redefining a method: A new implementation for the method of base class is given in the
derived class. Does not facilitate Dynamic binding.
Overriding a method: Redefining a virtual method of the base class in the derived class.
Virtual method facilitates Dynamic Binding.
The virtual function provides the ability to define a function in a base class and have a
function of the same name and type in a derived class called when a user calls the base
class function. That is often called run-time polymorphism, dynamic dispatch, or run-time
dispatch because the function called is determined at run time based on the type of the
object used.
The keyword virtual tells the compiler it should not perform early binding. Instead, it should
automatically install all the mechanisms necessary to perform late binding
Abstract Function:
1. It can be declared only inside abstract class.
2. It contains only method definition not the implementation.
3. It must be overridden
, "An Abstract Method must have to implement in the child class"
** I felt it is like.

foods and drinks days


Object Oriented Programming Tutorial

It is not necessary that an abstract method has to be implemented in a child class, if the
child class is also abstract..
1) An abstract method cant be a private method. 2) An Abstract method cant be
implemented in the same abstract class.
I would say ..if we are implementing an abstract class, you must have to override the
abstract methods from the base abstract class. Because.. Implementing the abstract
method is with override key word .Similar to Virtual method.
It is not necessary for a virtual method to be implemented in an inherited class.
Abstract function cannot have a body and MUST be overridden by child classes

Abstract function And Virtual function


An abstract function has no implemention and it can only be declared on an abstract class.
This forces the derived class to provide an implementation. A virtual function provides a
default implementation and it can exist on either an abstract class or a non-abstract class
Abstract method: When a class contains an abstract method, that class must be declared
as abstract. The abstract method has no implementation and thus, classes that derive from
that abstract class, must provide an implementation for this abstract method.

Virtual method: A class can have a virtual method. The virtual method has an
implementation. When you inherit from a class that has a virtual method, you can override
the virtual method and provide additional logic, or replace the logic with your own
implementation.
Virtual method change certain behavior In child class

fun days
Object Oriented Programming Tutorial

INNERCLASS

 Inner classes, also called Nested Classes, are nothing but classes that are defined within other classes. The
nesting is a relationship between classes, not objects.
 Inner classes have clearly two benefits, name control & access control. In Java, this benefit is not as important
because Java packages give the name control.
 Java inner classes have feature that makes them richer and more useful. An object of an inner class has an
implicit reference to the outer class object that instantiated it. Through this pointer, it gains access to any variable of
the outer object. Only static inner classes don’t have this pointer. It is actually invisible when we write the code, but
compiler takes care of it. Inner classes are actually a phenomenon of the compiler and not the JVM.
 Inner classes may be defined with following access modifiers : public, protected, private, or with default package
access.
The syntax for inner class is as follows:

1 [modifiers] class OuterClassName

2 {

3 code...

4 [modifiers] class InnerClassName


Object Oriented Programming Tutorial

5 {

6 code....

}
7
}
8

Inner Classes:

Following properties can be noted about Inner classes:

 The outer class (the class containing the inner class) can instantiate as many number of inner classobjects as it
wishes, inside it’s code.
 If the inner class is public & the containing class as well, then code in some other unrelated class can as well
create an instance of the inner class.
 In above case the inner class can be created as follows:

<OuterClassName>outerObj = new <OuterClassName>(arguments);


1
outerObj.<InnerClassName> innerObj = outerObj.new
2 <InnerClassName>(arguments);

 No inner class objects are automatically instantiated with an outer class object.
 If the inner class is static, then static inner class can be instantiated without an outer class instance, otherwise,
the inner class object must be associated with an instance of the outer class.
 Inner class code has free access to all elements of the outer class object that contains it, by name (no matter what
the access level of the elements is), if the inner class has a variable with same name then the outer class’s variable
can be accessed like this:
<OuterClassName>.this.<variableName>

 The outer class can call even the private methods of the inner class.

current weather
Object Oriented Programming Tutorial

Static Inner Classes:

Syntax for static inner classis as follows:

1
<access-specifier>
2 class OuterClassName

3 {

4 public static class <StaticInnerClassName>

5 {

6
}
7
}
8

for static inner classes following additional properties hold:

 Static members of the outer class are visible to the static inner class, whatever their access level be.
 Non-static members of the outer class are not available, because there is not instance of the outer class.
 An inner class may not have static members unless the inner class is itself marked as static.
 Sometimes static nested class are not referred to as inner class at all, as they don’t require outer classes instance.
 A static inner class is just like any other inner class, but it does not have the reference to its outer class object that
generated it.
There are two more types of inner classes, i.e local inner classes & anonymous inner
classes. The local inner class is defined within a method. Anonymous inner classes are
also defined with in a method but have no name.
Local Inner Classes:

Syntax of the local inner class is as follows:

1 <access-specifier>

2 class <OuterClassName>

3 {
Object Oriented Programming Tutorial

4 code...

5 <access-specifier> <return-type>
<MethodName>(<arguments>)
6
{
7 class <LocalInnerClassName>

8 {

9 code...

10 }

code...
11
}
12
code...
13

14
}
15

 Local classes are never declared with an access specifier (that is, public or private). Their scope is always
restricted to the block in which they are declared.
 Local classes have a great advantage: they are completely hidden from the outside world.
 They can not only access the instance variables but local variables of the method(in which they are defined) as
well, but the local variable has to be declared final.

Wrapper class
Wrapper class provides the mechanism to convert primitive into object and object into
primitive.
Those class we only use the primitive data type every data type have own wrapper class.
 Java is an object-oriented language and as said everything in java is an object. But what about the primitives? They
are sort of left out in the world of objects, that is, they cannot participate in the object activities, such as being
returned from a method as an object, and being added to a Collection of objects, etc. . As a solution to this problem,
Java allows you to include the primitives in the family of objects by using what are called wrapper classes.
 There is a wrapper class for every primitive date type in Java. This class encapsulates a single value for the
primitive data type. For instance the wrapper class for int is Integer, for float is Float, and so on. Remember that the
primitive name is simply the lowercase name of the wrapper except for char, which maps to Character, and int,
which maps to Integer.

worldwide weather
Object Oriented Programming Tutorial

 The wrapper classes in the Java API serve two primary purposes:
 To provide a mechanism to “wrap” primitive values in an object so that the primitives can be included in activities
reserved for objects, like as being added to Collections, or returned from a method with an object return value.
 To provide an assortment of utility functions for primitives. Most of these functions are related to various
conversions: converting primitives to and from String objects, and converting primitives and String objects to and
from different bases (or radix), such as binary, octal, and hexadecimal.
 The wrapper object of a wrapper class can be created in one of two ways: by instantiating the wrapper class with
the new operator or by invoking a static method on the wrapper class. We will explore this further in this article.

ABSTRACT CLASS
 An abstract class is something which is not concrete, something which is incomplete.
 Abstract class specifies what functionality is provided but not how that functionality is provided.
 An abstract class is a class that is declared abstract.
 Abstract class may or may not include abstract methods.
 Abstract classes cannot be instantiated, but they can be sub-classed.
 An abstract method is a method that is declared without an implementation (without braces, and followed by a
semicolon), like this:
 abstract void move To(double X, double Y);
 An abstract Method doesn't have method body.
 Use abstraction if you know something needs to be in class but implementation of that varies. e.g for Human class
you know there will be eating method but eating method implementation will be different for different country.
 If you declare any method in class as abstract,you have declare class also as abstract.

sunrise and sunset times


Object Oriented Programming Tutorial

 Abstract Class can contain abstract as well as non-abstract method.


 Eg.

?
package in.java4all.abstractclass;

public abstract class AbstractClasswithNonAbstractMethod {

abstract void abstractmethod();

public void nonabstractmethod(){

System.out.println("Abstract Class can hold non-abstract Method also");

moon phases
Object Oriented Programming Tutorial

 A class can be declared abstract without any abstract method also.

1
package in.java4all.abstractclass;
2

3
public abstract class AbstractClassWithoutAbstractMethod {
4

5 public void nonabstractmethod(){

6 System.out.println("Abstract Class can be declared without any abstract metho

7 }

8 public static void main(String[] args){

System.out.println("Main Method can be decalred inside Abstract Class");


9
}
10
}
11

 Abstract Class cannot be instantiated.

eclipses
Object Oriented Programming Tutorial

 Whichever concrete Class extends Abstract Class must implement abstract methods of the class.

 When to Use Abstract Class?


o The purpose of an abstract class is to specify the default functionality of an object and let its sub-classes to
explicitly implement that functionality.
o Suppose we were modeling the behavior of Human, by creating a class hierarchy that started with a base class
called Human.
o Human are capable of doing different things like seeing, sleeping and walking, but there are some common
operations as well like eating and speaking.
o Some common operations are performed by all human, but in a different way as well.
o When an operation (behavior) is performed in a different way, it is a good candidate for an abstract method (forcing
subclasses to provide a custom implementation).
o Let's look at a very primitive Human base class, which defines an abstract method for making a speaking (such as
French speaking French, an Indian Speaking Hindi, or an American speaking English).

Solstice and Equinox times


Object Oriented Programming Tutorial

1
public abstract Human
2
{
3
public void eating(Food food)
4 {

5 // do something with food....

6 }

8 public void sleeping (int hours)

9 {

// do something with sleeping


10
}
11
public abstract void speaking();
12
}
13

o Now, any Human that wants to be instantiated (like a Indian or American) must implement the speaking method -
otherwise it is impossible to create an instance of that class.
o Let's look at a Indian and American subclass that extends the Animal class.
?

public American extends Animal


2
{
3
public void speaking() {
4
System.out.println ("English English");
5
}

sunrise and sunset times


Object Oriented Programming Tutorial

 Why we cannot instantiate Abstract class in java?


o If the class had everything necessary to construct a meaningful object, the author wouldn't have declared it
abstract.
o The whole definition of "abstract class" is that it is an incompletely implemented parent, and therefore instances
wouldn't make sense.
o An Abstract class may or may not have abstract methods.
o So in that case JVM does not know how much memory it has to allocate for that abstract method because abstract
method does not have body implementation.
o So JVM will not able to allocate memory for the abstract methods when the time of creating instance to Abstract
class.
o So JVM unable to create the instance to Abstract class. So that we can't create the object for the Abstract class.
o It is also possible that we can create an Abstract class with all concrete methods, that is without any abstract
methods also.
o In that case also we can't create the instance for the Abstract class.
o Why because the abstract keyword simply indicates to JVM that the class cannot be instantiated.
o The designers of Java made the JVM that when it find abstract keyword for any class then JVM can't create the
instance for that class.

INTERFACE
 An interface in the Java programming language is an abstract type that is used to specify an interface classes
must implement. Interfaces are declared using the interface keyword, and may only contain signature and constant
declarations (variable declarations that are declared to be both static and final. An interface may never contain
method definitions.
 Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement
all of the methods described in the interface, or be an abstract class.
 As you've already learned, objects define their interaction with the outside world through the methods that they
expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for
example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press
the "power" button to turn the television on and off.

interface Interface
1
{
2
void test1();
3
abstract void test2();
Object Oriented Programming Tutorial

4 public abstract void test3();

5 }

O/P: Compile successful .

Note :Inside a interface all methods are Abstract & Public by default.

Ex.2

interface Interface1
1
{
2
void test1();
3
}
4 interface Interface2

5 {

6 void test2();

7 }

8 interface Interface3 extends Interface1,Interface2

{
9
void test3();
10
}
11
class A implements Interface3 /* All methods in the interface
12 must be implemented within a class.*/

13 {

public void test1()


14
{
15
System.out.println("test1");
16
}
17
public void test2()
Object Oriented Programming Tutorial

18 {

19 System.out.println("test2");

}
20
public void test3()
21
{
22
System.out.println("test3");
23
}
24
}
25 class InterfaceMain

26 {

27 public static void main(String[] args)

28 {

A d1 = new A();
29
d1.test1();
30
d1.test2();
31
d1.test3();
32
System.out.println("done");
33
}
34 }

35

36

37

38

moonrise and moonset times


Object Oriented Programming Tutorial

O/P:

Note: An interface can't inherit from a class in Java but only we can implements.

Concrete Class
A concrete class is a class that can be used to create an object. An abstract class cannot
be used to create an object (you must extend an abstract class and make a concrete class
to be able to then create an object).
if we override all pure virtual function in derived class then it becomes concrete class

The object of these classes can be created

An abstract class is meant to be used as the base class from which other classes are derived.
The derived class is expected to provide implementations for the methods that are not
implemented in the base class. A derived class that implements all the missing functionality is
called a concrete class.
A concrete class in java is any such class which has implementation of all of its inherited
members either from interface or abstract class.
Concrete and Abstract are opposite of each other. So let me tell you something about
abstract classes so that you can easily understand Concrete Classes

Abstract Class
An Abstract Class is a class that has one or more pure virtual member functions. You
cannot make an object (instance) of an Abstract Class
Without "virtual" you get "early binding". Which implementation of the method is used gets
decided at compile time based on the type of the pointer that you call through.

Abstract classes whose object can’t be created are call abstract class.

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

distance between cities


Object Oriented Programming Tutorial

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs. So, we
perform method overloading to figure out the program quickly.

These are just used for inheritance

If we create any pure virtual function in class then it becomes abstract class

1. Are incomplete classes and it must be sub classed in order to use


2. Must be Followed by abstract keyword
3. Must have at least Zero or more abstract method(Method which does not have body)

Advantage of method overloading?

Method overloading increases the readability of the program.

Different ways to overload the method


There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Abstract and Concrete Classes

All classes can be designated as either abstract or concrete. Concrete is the default. This means
that the class can have (direct) instances. In contrast, abstract means that a class cannot have
its own (direct) instances. Abstract classes exist purely to generalize common behavior that
would otherwise be duplicated across (sub)classes. We'll illustrate this with the following
diagram.

calendars
Object Oriented Programming Tutorial

Concrete classes that can be instantiated; abstract classes cannot directly be instantiated.

Abstract Class and Concrete Class

Abstract classes are super classes which contain abstract methods and are defined such that concrete
subclasses are to extend them by implementing the methods Abstract class cannot be used to
create an object. Whereas, concrete class can be used to create an object.
Concrete means’ ‘existing in reality or in real experience; perceptible by the senses; real''.
Whereas, abstract means 'not applied or practical; theoretical'.
An abstract class can't be instantiated. Whereas, a concrete one can.
An abstract class is one that has one or more pure virtual function. Whereas
a concrete class has no pure virtual functions

1. Only abstract classes can have abstract members.


2. A non-abstract class that inherits from an abstract class must override its abstract
members.
3. An abstract member is implicitly virtual.
4. An abstract member cannot provide any implementation (abstract is called pure
virtual in some languages).

derived class and concrete class


Base-class vs. derived class is an orthogonal concept to abstract class vs. concrete class.

A base class is one that does not inherit from any other class. A derived class does inherit
from another class.

An abstract class is one that has one or more pure virtual functions. A concrete class has
no pure virtual.

An abstract class can be either a base class or a derived class (it is derived from another
abstract class). A concrete class can also be either base or derived. You can even derive
an abstract class from a concrete class, by adding a pure virtual function to the derived
class. But in general use, there is one base abstract class and one or more concrete
derived classes.

Concrete class has all its method implemented

calendars today date


Object Oriented Programming Tutorial

Interface Class

An interface in java is a blueprint of a class. It has static constants and abstract methods
only.

The interface in java is a mechanism to achieve fully abstraction. There can be only
abstract methods in the java interface not method body. It is used to achieve fully
abstraction and multiple inheritance in Java.

Java Interface also represents IS-A relationship.

It cannot be instantiated just like abstract class.

Why use Java interface?


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

 It is used to achieve fully abstraction.


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

Multiple inheritance is not supported through class in java but it is


possible by interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in


case of class. But it is supported in case of interface because there is no ambiguity as
implementation is provided by the implementation class

Difference Between Interface and Abstract Class

"An interface is a contract: the guy writing the interface says, "hey, I accept things looking
that way", and the guy using the interface says "OK, the class I write looks that way".
An interface is an empty shell, there are only the signatures (name / params / return
type) of the methods. The methods do not contain anything. The interface can't do
anything. It's just a pattern."

printable calendar
Object Oriented Programming Tutorial

Difference between abstract class and interface


Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and Interface can have only
non-abstract methods. abstract methods.

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


inheritance.

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

4) Abstract class can have static methods, Interface can't have static methods,
main method and constructor. main method or constructor.

5) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

timers
Object Oriented Programming Tutorial

Concrete class vs. Abstract class vs. Interface.


1. A concrete class has concrete methods, i.e., with code and other functionality. This class
a may extend an abstract class or implements an interface.

2. An abstract class must contain at least one abstract method with zero or more concrete
methods

3. An interface must contain only method signatures and static members.

4. An interface does not have definitions of the methods declared in it.

5. An abstract class may have some definition and at least one abstract method.

6. A subclass of an abstract class must either implement all the abstract methods of the
abstract class or declare itself as abstract.

Inheritance
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.

The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of parent class, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

The extends keyword indicates that you are making a new class that derives from an
existing class.

In the terminology of Java, a class that is inherited is called a super class. The new class is
called a subclass.

Why use inheritance in java


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

alarm clock
Object Oriented Programming Tutorial

Types of inheritance in java


On the basis of class, there can be five types of inheritance in java: single, multilevel and
hierarchical multiple and hybrid

Abstraction

Hiding internal details and showing functionality is known as abstraction. For


example: phone call, we don't know the internal processing. We use abstract class and
interface to achieve abstraction.

 Abstraction is the concept of hiding irrelevant details. In other words make complex system simple by hiding the
unnecessary detail from the user.
 Abstract class specifies what functionality is provided but not how that functionality is provided.
 For example one does not want to understand how engine works. Similarly one does not have to understand the
internal implementation of the software objects.
 Abstraction provides a way to hide the less essential properties so as to reduce complexity and increase efficiency.

Abstraction advantage
Abstraction main advantage is that every user will get data according to their exact requirement. User will not get
confused with unnecessary data.
Abstraction in Java or Object oriented programming is a way to segregate implementation from interface.
Abstraction in Java is achieved by using interface and abstract class in Java.
An interface or abstract class is something which is not concrete , something which is incomplete.

stopwatch
Object Oriented Programming Tutorial

Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.

Encapsulation: Is hiding unwanted/un-expected/propriety implementation details from the


actual users of object

A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here

Encapsulation in java is a process of wrapping code and data together into a single unit,
for example capsule i.e. mixed of several medicines.

We can create a fully encapsulated class in java by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.

 Encapsulation is the technique of making the fields in a class private and providing access to the fields through
public methods. Encapsulation is also called as data hiding.
 The benefits of encapsulation:
 The ability to modify our implemented code without breaking the code of others who use our code
 Encapsulation gives maintainability, flexibility, and extensibility to our code.
 The fields of a class can be made read-only or write-only.
 A class can have total control over of what is stored in its fields.
 A class can change the data type of a field, and users of the class do not need to the changes any of theircode.

Advantage of Encapsulation in java

By providing only setter or getter method, you can make the class read-only or write-
only.

countdown
Object Oriented Programming Tutorial

It provides you the control over the data. Suppose you want to set the value of id i.e.
greater than 100 only, you can write the logic inside the setter method.

Abstraction : Abstraction means to show What part of functionality.


Encapsulation : Encapsulation means to hide the How part of the functionality.
Encapsulation is the packing of data and functions operating on that data into a single
component and restricting the access to some of the object's components.
Encapsulation means that the internal representation of an object is generally hidden from
view outside of the object's definition.
Abstraction is a mechanism which represent the essential features without including
implementation details.
Encapsulation:-- Information hiding.
Abstraction:-- Implementation hiding.
Encapsulation is wrapping up complexity in one capsule
Example:

class foo{
private:
int a, b;
public:
foo(): a(0), b(0)
{ }

foo(int x, int y): a(x), b(y)


{ }

int add()
{
return a+b;
}
}
Internal representation of any object of foo class is hidden outside the class. -->
Encapsulation.
foo foo_obj(3, 4);
int sum = foo_obj.add();
Implementation of method add is hidden. --> Abstraction.
Use of foo_obj object above is also an example of abstraction as it is used without any
details of its implementation.
Abstraction--- Hiding Implementation--at Design---Using Interface/Abstract classes

Encapsulation--Hiding Data --At Development---Using access modifiers(public/private)

new year countdown


Object Oriented Programming Tutorial

Encapsulation is -

 Hiding Complexity,
 Binding Data and Function together,
 Making Complicated Method's Private,
 Making Instance Variable's Private,
 Hiding Unnecessary Data and Functions from End User.
Encapsulation implements Abstraction.

And Abstraction is -

 Showing What’s Necessary,


 Data needs to abstract from End User,
Encapsulation is the ability to treat something as a single thing, even though it may be
composed of many complex parts or ideas. For example, I can say that I'm sitting in a
"chair" rather than referring to the many various parts of that chair each with a specific
design and function, all fitting together precisely for the purpose of comfortably holding my
butt a few feet away from the floor.
Abstraction is enabled by encapsulation. Because we encapsulate objects, we can think
about them as things which relate to each other in some way rather than getting bogged
down in the subtle details of internal object structure. Abstraction is the ability to consider
the bigger picture, removed from concern over little details. The root of the word is abstract
as in the summary that appears at the top of a scholarly paper, not abstract as in a class
which can only be instantiated as a derived subclass.
I can honestly say that when I plop my butt down in my chair, I never think about how the
structure of that chair will catch and hold my weight. It's a decent enough chair that I don't
have to worry about those details. So I can turn my attention toward my computer. And
again, I don't think about the component parts of my computer. I'm just looking at a part of a
webpage that represents a text area that I can type in, and I'm communicating in words,
barely even thinking about how my fingers always find the right letters so quickly on the
keyboard, and how the connection is ultimately made between tapping these keys and
posting to this forum. This is the great power of abstraction. Because the lower levels of the
system can be trusted to work with consistency and precision, we have attention to spare
for greater work.

week number
Object Oriented Programming Tutorial

Data Encapsulation simply means wrapping and controlling access of logically grouped
data in a class. It is generally associated with another keyword

A simple example would be defining a private variable and giving access to it using getter
and setter methods or making a method private as it's only use is withing the class. There is
no need for user to know about these methods and variables.

Note : It should not be misunderstood that encapsulation is all about data hiding only. When
we say encapsulation, emphasis should be on grouping or packaging or bundling related
data and behavior together.
Data Abstraction on the other hand is concept of generalizing so that the underneath
complex logic is not exposed to the user. In Java this is achieved by
using interfaces and abstract classes.
Example -

Lets say we have an interface Animal and it has a function makeSound(). There are two
concrete classes Dog and Cat that implement this interface. These concrete classes have
separate implementations of makeSound() function. Now lets say we have a animal(We get
this from some external module). All user knows is that the object that it is receiving is some
Animal and it is the users responsibility to print the animal sound. One brute force way is to
check the object received to identify it's type, then typecast it to that Animal type and
then call makeSound() on it. But a neater way is to abstracts thing out. Use Animal as
a polymorphic reference and call make Sound() on it. At runtime depending on what the
real Object type is proper function will be invoked.
Abstraction is generalized term. i.e. Encapsulation is subset of Abstraction.

day facts calculator


Object Oriented Programming Tutorial

weekdays calculator
Object Oriented Programming Tutorial

Difference Between Abstraction and Encapsulation.

Abstraction Encapsulation

1. Abstraction solves the problem in 1. Encapsulation solves the problem


the design level. in the implementation level.

2. Abstraction is used for hiding the 2. Encapsulation means hiding the


unwanted data and giving relevant code and data into a single unit to
data. protect the data from outside world.

3. Abstraction lets you focus on 3. Encapsulation means hiding the


what the object does instead of how internal details or mechanics of how
it does it an object does something.

4. Abstraction- Outer layout, used 4. Encapsulation- Inner layout,


in terms of design. used in terms of implementation.
Object Oriented Programming Tutorial

For Example:- For Example:- Inner


Implementation detail of a Mobile
Outer Look of a Mobile Phone, like Phone, how keypad button and
it has a display screen and keypad Display Screen are connect with
buttons to dial a number. each other using circuits.

Abstraction refers to the act of representing essential features without including the
background details or explanations.
Encapsulation is a technique used for hiding the properties and behaviors of an object and
allowing outside access only as appropriate. It prevents other objects from directly altering
or accessing the properties or methods of the encapsulated object.
Difference between abstraction and encapsulation
1.Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation
(information hiding) prevents clients from seeing it’s inside view, where the behavior of the
abstraction is implemented.

2.Abstraction solves the problem in the design side while Encapsulation is the
Implementation.

3.Encapsulation is the deliverable of Abstraction. Encapsulation barely talks about grouping


up your abstraction to suit the developer needs

Abstraction : Abstraction is process in which you collect or gather relevant data and
remove non-relevant data. (And if you have achieved abstraction, then encapsulation also
achieved.)
Encapsulation: Encapsulation is a process in which you wrap of functions and members in
a single unit. Means You are hiding the implementation detail. Means user can access by
making object of class, he/she can't see detail.
Difference between Abstraction and Encapsulation :-
Abstraction
1. Abstraction solves the problem in the design level.
2. Abstraction is used for hiding the unwanted data and giving relevant data.
3. Abstraction lets you focus on what the object does instead of how it does it.
4. Abstraction- Outer layout, used in terms of design. For Example:- Outer Look of a
Mobile Phone, like it has a display screen and keypad buttons to dial a number.

business days calculator


Object Oriented Programming Tutorial

Encapsulation
1. Encapsulation solves the problem in the implementation level.
2. Encapsulation means hiding the code and data into a single unit to protect the data
from outside world.
3. Encapsulation means hiding the internal details or mechanics of how an object does
something.
4. Encapsulation- Inner layout, used in terms of implementation. For Example:- Inner
Implementation detail of a Mobile Phone, how keypad button and Display Screen are
connect with each other using circuits

Real Life Difference Between Encapsulation and Abstraction


Encapsulate means to hide. Encapsulation is also called data hiding.You can think
Encapsulation like a capsule (medicine tablet) which hides medicine inside it. Encapsulation
is wrapping, just hiding properties and methods. Encapsulation is used for hide the code
and data in a single unit to protect the data from the outside the world. Class is the best
example of encapsulation.

Abstraction refers to showing only the necessary details to the intended user. As the name
suggests, abstraction is the "abstract form of anything". We use abstraction in programming
languages to make abstract class. Abstract class represents abstract view of methods and
properties of class.

Implementation Difference Between Encapsulation and Abstraction


1. Abstraction is implemented using interface and abstract class while Encapsulation is
implemented using private and protected access modifier.
2. OOPS makes use of encapsulation to enforce the integrity of a type (i.e. to make sure
data is used in an appropriate manner) by preventing programmers from accessing
data in a non-intended manner. Through encapsulation, only a predetermined group of
functions can access the data. The collective term for datatypes and operations
(methods) bundled together with access restrictions (public/private, etc.) is a class.

date duration calculator


Object Oriented Programming Tutorial

DIFFERENCE BETWEEN ENCAPSULATION AND


ABSTRACTION

 Abstraction and Encapsulation in Java are two important Object oriented programming
concept and they are completely different to each other.

 Encapsulation is a process of binding or wrapping the data and the codes that
operates on the data into a single entity. This keeps the data safe from outside
interface and misuse.

age calculator
Object Oriented Programming Tutorial

 Abstraction is the concept of hiding irrelevant details. In other words make complex
system simple by hiding the unnecessary detail from the user.

 Abstraction is implemented in Java using interface and abstract class while


Encapsulation is implemented using private, package-private and protected access
modifier.

Polymorphism can be achieved through overriding. Put in short words, polymorphism refers
to the ability of an object to provide different behaviors (use different implementations)
depending on its own nature. Specifically, depending on its position in the class hierarchy.
Inheritance

 Polymorphism is an important Object Oriented concept and widely used in all Object Oriented Programming
Language.
 Polymorphism word comes from ancient Greek where poly means many. Polymorphism means many form.
 Polymorphism in Java means same object behave differently in different place.
 For e.g Lady is one of the example polymorphism. Same Lady object will be behave differently when she is sister,
wife and mother.

Polymorphism in java is a concept by which we can perform a single action by different


ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in java: compile time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.

If you overload static method in java, it is the example of compile time polymorphism. Here,
we will focus on runtime polymorphism in java.

Polymorphism means more than one form, same object performing different operations
according to the requirement.

Polymorphism can be achieved by using two ways, those are

1. Method overriding
2. Method overloading

date calculator
Object Oriented Programming Tutorial

Method overloading means writing two are or more methods in the same class by using
same method name, but passing the parameters is different.
Method overriding means we use the method names in the different classes, that means
parent class method is used in the child class.
Actually, there are multiple forms of polymorphism and there is quite some controversy over
it; you may even see CS professors who cannot define it properly. I am aware of three
types:

 ad-hoc polymorphism (looks like a duck and walks like a duck => is a duck). Can be
seen in Haskell and Python for example.
 generic polymorphism (where a type is an instance of some generic type). Can be seen
in C++ for example (vector of int and vector of string both have a member function
size).
 subtype polymorphism (where a type inherits from another type). Can be seen in most
OO programming languages (i.e. Triangle is a Shape).
ad hoc polymorphism
ad hoc polymorphism is the act of providing multiple implementations of the same method
for different parameter types. In OOP, it's generally known as method overloading. For
example:
public String format(int a) {
return String.format("%2d", a);
}

public String format(Date a) {


return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(a);
}
Both format methods share a single interface but work on entities of different types.
Parametric polymorphism
Parametric polymorphism is the act of making a class (or method) work on a type that is
itself a parameter of the class (or method). It's often referred to as generics.
For example, Java's List[T] expects a parameter T at instantiation time, and this parameter
defines the type of the resulting object.
Note for purists that I'm purposefully ignoring raw types as I feel they'd just muddy the
waters in this context.
List[String] and List[Date] share a single interface, but work on (and are) different types.
Subtype polymorphism
Subtype polymorphism is probably what you initially meant in your question: it's the act of
providing a single interface to multiple implementations of the same type.
To use the customary example: Animal provides a contract that all implementations must
respect. Dog is an Animal, and as such supports all operations that Animal declares.
According to the Liskov substitution principle, this allows you to use an instance
of Dog where an instance of Animal is expected (but not the other way around).
Object Oriented Programming Tutorial

If Cat and Dog are both subclasses of Animal, then they share a single interface but are in
fact different types.
I'm going off in a bit of a tangent here, but subtype polymorphism is (I think) the only one
that allows overriding: the act of redefining the behavior of a method defined by a parent
class. This is often confused with overloading which, as we saw before, is a type of
polymorphism and doesn't in fact need sub classing (nor does it need classes, really).
There are two kinds of polymorphism :
1. Compile Time (Static) Polymorphism or (Ad Hoc) Polymorphism.
that is simply Method Overloading and Operator overloading
2. Run Time or (Dynamic) Polymorphism.
The first Term is inherited from The java and C++ terminology.
But in the .Net terminology only the second one (I mean Run Time Polymorphism) is
really supposed as Polymorphism and simply called as Polymorphism.
And as far as I know there are three methods for implementing (Run Time) Polymorphism.
1. Parametric Polymorphism or simply the use of Generics(Templates in c++).

2. Inheritance-Based Polymorphism or Subtyping.

3. Interface-Based Polymorphism.

 There are two kind of polymorphism


 Compile time polymorphism (static binding or method overloading)
 Runtime polymorphism (dynamic binding or method overriding)
 Compile time polymorphism (static binding or method overloading)
 In this flow of the method will be decided the compile time of the code.
 Method Overloading
o When Java Programmer declare two methods of the same name but with different signature in a same class, this
concept is called as Method overloading.
Different signature means change in number of arguments or change in type of arguments.
o System.out.println() is popular example of method overloading because printly() method takes string,int,float or any
other data type.

 Few points Method Overloading


o Overloaded method are loaded and bonded at compile time.
o Overloaded methods are fast because they bonded at compile time.

hijrahi holidays
Object Oriented Programming Tutorial

 What do you mean by different method signature for method Overloading in Java
o If number of argument is different.
o If type of argument is different.
o If sequence of argument is different ,only when arguments of different types

Runtime Polymorphism in Java


Class A{
void method(int a, string x){
}
void method(string x,int a){
}

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.

In this process, an overridden method is called through the reference variable of a


superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.

Runtime Polymorphism with data member


Method is overridden not the data members, so runtime polymorphism can't be achieved
by data members.

In the example given below, both the classes have a data member speed limit, we are
accessing the data member by the reference variable of Parent class which refers to the
subclass object. Since we are accessing the data member which is not overridden, hence
it will access the data member of Parent class always.

christian holidays
Object Oriented Programming Tutorial

Runtime Polymorphism with Multilevel Inheritance


1. class Animal{
2. void eat(){System.out.println("eating");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("eating fruits");}
7. }
8.
9. class BabyDog extends Dog{
10. void eat(){System.out.println("drinking milk");}
11.
12. public static void main(String args[]){
13. Animal a1,a2,a3;
14. a1=new Animal();
15. a2=new Dog();
16. a3=new BabyDog();
17.
18. a1.eat();
19. a2.eat();
20. a3.eat();
21. }
22. }

Chinese holidays

S-ar putea să vă placă și