Object Oriented Programming Tutorial - PowerPoint PPT Presentation

About This Presentation
Title:

Object Oriented Programming Tutorial

Description:

Features 1.1 Shared with non-OOP predecessor languages 1.2 Objects and classes 1.3 Class-based vs prototype-based 1.4 Dynamic dispatch/message passing 1.5 Encapsulation 1.6 Composition, inheritance, and delegation 1.7 Polymorphism 1.8 Open recursion – PowerPoint PPT presentation

Number of Views:759

less

Transcript and Presenter's Notes

Title: Object Oriented Programming Tutorial


1
Object Oriented Programming Tutorial
Contents Features 1.1 Shared with non-OOP
predecessor languages 1.2 Objects and
classes 1.3 Class-based vs prototype-based 1.4
Dynamic dispatch/message passing 1.5
Encapsulation 1.6 Composition, inheritance,
and delegation 1.7 Polymorphism 1.8 Open
recursion
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.
2
Object Oriented Programming Tutorial
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 s1new student
("Martin") Student s2new 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 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
3
Object Oriented Programming Tutorial
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
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.
4
Object Oriented Programming Tutorial
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 s1new student ("Martin")
Student s2new student("Kumar") The s1, s2 are
having object of class Student
time zone 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
5
Object Oriented Programming Tutorial
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, mobile, bed, keyboard, mouse, chair etc. Class is a group of similar objects.
3) Object is a physical entity. Class is a logical entity.
4) Object is created through new keyword mainly e.g. Student s1 new Student() Class is declared using class keyword e.g. 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. deserializati
on. Aggregation
If a class has an entity reference, it is known
as Aggregation. Aggregation represents HAS-A
relationship.
6
Object Oriented Programming Tutorial
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 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 nameand then property name
this sign is call scope resolution operator
7
Object Oriented Programming Tutorial
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 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.
8
Object Oriented Programming Tutorial
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 nonstatic
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 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
9
Object Oriented Programming Tutorial
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 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
10
Object Oriented Programming Tutorial
Static vs non static
2 Memory is allocated for these variable whenever an object is created Memory is allocated for these variable at the time of loading of the class.
3 Memory is allocated multiple time whenever a new object is created. Memory is allocated for these variable only once in the program.
4 Non-static variable also known as instance variable while because memory is allocated whenever instance is created. Memory is allocated at the time of loading of class so that these are also known as class variable.
5 Non-static variable are specific to an object Static variable are common for every object that means there memory location can be sharable by every object reference or same class.
6 Non-static variable can access with object reference. Syntax Static variable can access with class reference. Syntax
obj_ref.variable_name class_name.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.
11
Object Oriented Programming Tutorial
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 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.
12
Object Oriented Programming Tutorial 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 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
13
Object Oriented Programming Tutorial
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
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
14
Object Oriented Programming Tutorial
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 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
15
Object Oriented Programming Tutorial
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 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.
16
Object Oriented Programming Tutorial
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
gairab Child class Function car(int c,int
b) Return gairab
meeting planner 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.
17
Object Oriented Programming Tutorial
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. 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
18
Object Oriented Programming Tutorial
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 nonmember 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 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.
19
Object Oriented Programming Tutorial
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.
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 readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its super class.
2) Method overloading is performed within class. Method overriding occurs in two classes that have IS-A (inheritance) relationship.
20
Object Oriented Programming Tutorial
3) In case of method overloading, parameter must be different. In case of method overriding, parameter must be same.
4) Method overloading is the example of compile time polymorphism. Method overriding is the example of run time polymorphism.
5) In java, method overloading can't be performed by changing return type of the method only. Return type Return type must be same or 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 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
21
Object Oriented Programming Tutorial
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 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
22
Object Oriented Programming Tutorial
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 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? Ansiyes, that is current class
instance (You cannot use return type yet it
returns a value).
23
Object Oriented Programming Tutorial
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-gt_construct() _const
ruct 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. 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
24
Object Oriented Programming Tutorial
Car()
3 4 5 6 7 8
Car(String s)
9 10 11

holidays and observances 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.
25
Object Oriented Programming Tutorial
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 Class a _destructor
first destructor destroy the resources then
destroy object Obj jnew b() //resource Constr
uctor 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
26
Object Oriented Programming Tutorial
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 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
27
Object Oriented Programming Tutorial
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 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.
28
Object Oriented Programming Tutorial
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 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.
29
Object Oriented Programming Tutorial
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
30
Object Oriented Programming Tutorial
INNERCLASS
Instance Inner class
Local Inner class
Non Static
Inner class
Anonymous Inner class
Static
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
31
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
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 ltOuterClassNam
egt.this.ltvariableNamegt The outer class can
call even the private methods of the inner class.
current weather
32
Object Oriented Programming Tutorial
Static Inner Classes Syntax for static inner
classis as follows
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 ltaccess -specifiergt
2 class ltOuterClassNamegt
3
33
Object Oriented Programming Tutorial
code...
4
ltaccess-specifiergt ltreturn-typegt
ltMethodNamegt(ltargumentsgt)
5
6

7
class ltLocalInnerClassNamegt
8

code...
9

10
code...
11
code...
12 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
34
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
35
Object Oriented Programming Tutorial
J) AbtractClass.java S3 I package
in.java4all.abstractclass a public class
abstract void mthoMlli
3 The abstract method methodl in type AbtractClass can only be defined by an abstract class 3 The abstract method methodl in type AbtractClass can only be defined by an abstract class 3 The abstract method methodl in type AbtractClass can only be defined by an abstract class
2 J quick fixes available rfgt Remove 'abstract' modifier 1
2 J lttgt MaketvDe 'AbtractClass' abstract 1
Press F2 for focus
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
36
Object Oriented Programming Tutorial
A class can be declared abstract without any
abstract method also.
?
1 2 3 4 5 6 7 8 9 10 11
package in.java4all.abstractclass public
abstract class AbstractClassWithoutAbstractMethod
public void nonabstractmethod() System.out.prin
tln("Abstract Class can be declared without any
abstract metho public static void main(String
args) System.out.println("Main Method can be
decalred inside Abstract Class")
package in.java4all.abstractclass
public abstract class AbstractClassCannotBelnstant
iated public void nonabstractmethodl()
B
AbstractClassCannotBelnstantiated abnew

Cannot instantiate the type AbstractClassCannotB
elnstantiated
gt
Press F2' for focus
Abstract Class cannot be instantiated.
eclipses
37
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
38
Object Oriented Programming Tutorial
1 2 3
public abstract Human
public void eating(Food food)
4

5
// do something with food....
6
7
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 3 public void
speaking() 4 System.out.println ("English
English") 5
sunrise and sunset times
39
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
40
Object Oriented Programming Tutorial
4 public abstract void test3() 5 6
O/P Compile successful .
Note Inside a interface all methods are
Abstract Public by default. Ex.2
41
Object Oriented Programming Tutorial
18
19 System.out.println("test2")
20 public void test3()
21 public

22 System.out.println("test3")
23
24
25 class InterfaceMain InterfaceMain
26
27 public static void main(String args)
28
29 A d1 new A() d1.test1()
30 A d1 new A() d1.test1()
d1.test2()
31 d1.test3()
32 System.out.println("done")
33
34
Write a Comment
User Comments (0)
About PowerShow.com