SlideShare a Scribd company logo
Java Session 2
Object Orientation
• Class
• Object
• Encapsulation

• Inheritance
• Polymorphism
• Abstraction
• Overriding and overloading
• Reference variable casting
• Legal return types
• Constructors and instantiation
OOP
 Class : A class can be defined as a template/blue print that describes the
behaviors/states that object of its type support.
Ex : http://ideone.com/kBqxR1

Object : Objects have states and behaviors. It is an instance of a class.
Example: A dog has states - color, name, breed as well as behaviors -wagging,
barking, eating.
Refer example : http://ideone.com/FBN06D
Refer docs : http://docs.oracle.com/javase/tutorial/java/concepts/object.html
Object creation
 Using new keyword : Most common way to create object.
Detect errors like class not found at compile time.
TestObject object = new TestObject()
 Using Class. forName() : Useful if we have class name with default
constructor
TestObject object =(TestObject)Class.forName(“package.TestObject”).newInstance()

 Using Clone() : Used for creating copy of an existing object
TestObject originalObject = new TestObject();
TestObject cloneObject = originalObject.clone();
 Using object deserialization : Useful for creating object from serialized
form
ObjectInputStream inputStream = new ObjectInputStream(anInputStream);
TestObject object = (TestObject)inputStream.readObject();
Refer example here : https://gist.github.com/rajeevprasanna/8493409
•

Variable types or blocks. They
Local variables : Variables defined inside methods, constructors
declared and initialized within the method and destroyed after method execution.

cannot use access modifier for local variables.
No default value. Should be declared and initialized before first use.
Implemented at Stack level.

•

Instance variables : Declared within a class but outside any method. These are
initialized when class is created and lives till the object is destroyed.

When a space is created for an object in the heap, a slot for each instance variable value is
created
Prefer declaring variable as instance variables only if they are used at more than one
method, constructor or block
They have access modifiers and visible across the whole class and initialized to default
values
for numbers default is 0, for Boolean default is false, for object reference it is null.

•

Class Variables :

similar to instance variables with static modifier

Static variables are stored in static memory. One copy is shared across all instances.
Make them final to avoid getting modified by any one during life cycle as it last for entire
program
Encapsulation
 Encapsulation is the ability to package data, related behavior in an object bundle
and controls/restrict access to them from other objects. It is all about packaging
related stuff together and hide them from external elements.
 Encapsulation is not all about data hiding only. It is all about grouping or
packaging related data and behavior.
 Primary benefit of encapsulation is better maintainability. It gives total control
over class fields to the class. Also users will not aware of internal implementations.
Better ways to encapsulate object :
 Keep instance variables protected(with an access modifier, often private)
 Make public accessor methods, and force calling code to use those methods rather
than directly accessing the instance variables.
 For the methods, use the JavaBeans naming convention of
ser<somePropertyName> and get<somePropertyName>
Refer examples here : https://gist.github.com/rajeevprasanna/8494434
Inheritance
 IS-A relationship
is-a relationship is totally based on inheritance which can be class type or interface inheritance
ex: it is like saying “A is a B type of thing”. Apple is a fruit, car is a vehicle

Inheritance is a unidirectional. Ex : House is a building but building is not a house.
we can say is-a relationship if it uses extends or implements keyword. Tightly coupled
ex : https://gist.github.com/rajeevprasanna/8499616
https://gist.github.com/rajeevprasanna/8500052

 HAS-A relationship(Composition relationship)
composition or has-A relationship means use of instance variables that are reference to other
objects.

Composition is dynamic binding (run time binding) while Inheritance is static binding
(compile time binding) . It is loosely coupled.
ex : https://gist.github.com/rajeevprasanna/8499902
https://gist.github.com/rajeevprasanna/8500118

 InstanceOf : https://gist.github.com/rajeevprasanna/8499735
Inheritance…
Two most common reasons to use inheritance are :

•

To promote code reuse
ex : https://gist.github.com/rajeevprasanna/8499902

•

To use polymorphism
ex : https://gist.github.com/rajeevprasanna/8499990

Check differences here : http://guruzon.com/1/oop-concepts/inheritance-andcomposition/difference-between-is-a-and-has-a-relationships-tutorial-example
Polymorphism
•

Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object.

•

Any Java object that can pass more than one IS-A test is considered to be polymorphic.
In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own
type and for the class Object.

•

Only possible way to access an object is through a reference variable. A reference variable
can be of only one type. Once declared, the type of a reference variable cannot be changed.

•

The reference variable can be reassigned to other objects provided that it is not declared
final. The type of the reference variable would determine the methods that it can invoke on
the object

•

A reference variable can refer to any object of the same type as the declared reference, or—
this is the big one—it can refer to any subtype of the declared type!

•

A reference variable can be declared as a class type or an interface type. If the variable is
declared as an interface type, it can reference any object of any class that implements the
interface.

•

A class cannot extend more than one class. That means one parent per class. Any given
class might have multiple classes up its inheritance tree, but that's not the same as saying a
class directly extends two classes.
Ex : https://gist.github.com/rajeevprasanna/8500554
Polymorphism types…

•

Polymorphism allows you define a Super type and have multiple subtype implementations

•

Polymorphism is of two types :
1. Compile time or static polymorphism
2. Runtime or dynamic polymorphism

• Compile time polymorphism : Method overloading is a compile time polymorphism
As we can have multiple subtype implementations for a super type, the compiler determines
which type to be invoked at the compile time.
ex : https://gist.github.com/rajeevprasanna/8500616

• Runtime polymorphism : Method overriding is a runtime polymorphism.
As we can have multiple subtype implementations for a super type, Java virtual machine
determines the proper type to be invoked at the runtime.
Ex : https://gist.github.com/rajeevprasanna/8500647
Overriding method rules :
• The argument list must exactly match that of the overridden method. If they
don't match, you can end up with an overloaded method you didn't intend
• The return type must be the same as, or a subtype of, the return type declared in
the original overridden method in the superclass. (More on this in a few pages
when we discuss covariant returns.)
• The access level can't be more restrictive than the overridden method's.
• The access level CAN be less restrictive than that of the overridden method.
• Instance methods can be overridden only if they are inherited by the subclass. A
subclass within the same package as the instance's superclass can override any
superclass method that is not marked private or final. A subclass in a different
package can override only those non-final methods marked pub- lic or protected
(since protected methods are inherited by the subclass).
• The overriding method CAN throw any unchecked (runtime) exception,
regardless of whether the overridden method declares the exception.

• The overriding method must NOT throw checked exceptions that are new or
broader than those declared by the overridden method. For example, a method
that declares a FileNotFoundException cannot be overridden by a method that
declares a SQLException, Exception, or any other non-runtime exception unless
it's a subclass of FileNotFoundException.
Overriding method rules (contd … ):
• The overriding method can throw narrower or fewer exceptions. Just because
an overridden method "takes risks" doesn't mean that the overriding subclass'
exception takes the same risks. Bottom line: an overriding method doesn't have
to declare any exceptions that it will never throw, regardless of what the
overridden method declares.
• You cannot override a method marked final.
• You cannot override a method marked static.
• If a method can't be inherited, you cannot override it. Remember that overriding
implies that you're reimplementing a method you inherited!
 Superclass method invoker : https://gist.github.com/rajeevprasanna/8500736

• If a method is overridden but you use a polymorphic (supertype) reference to
refer to the subtype object with the overriding method, the compiler assumes
you’re calling the supertype version of the method. If the supertype version
declares a checked exception, but the overriding subtype method does not, the
compiler still thinks you are calling a method that declares an exception.
ex : https://gist.github.com/rajeevprasanna/8500769
Examples of Legal and Illegal Method Overrides(for the above
example) :
Polymorphism in Overloaded and Overridden Methods:
•
•

polymorphism doesn't determine which overloaded version is called; polymorphism does
come into play when the decision is about which overridden version of a method is
called.
Ex with both overloading and overriding :

https://gist.github.com/rajeevprasanna/8500851
• We can overload a method without overriding in subclass.

Ex : https://gist.github.com/rajeevprasanna/8500874
Differences Between Overloaded and Overridden Methods :

Check covarient explanation here :
https://blogs.oracle.com/sundararajan/entry/covariant_return_types_in_java
Reference variable casting
 Upcasting
 Downcasting
• Animal animal = new Dog();
But what happens when you want to use that animal reference variable to invoke a
method that only class Dog has?

ex : https://gist.github.com/rajeevprasanna/8501055
• Unlike downcasting, upcasting (casting up the inheritance tree to a more general
type) works implicitly (i.e., you don't have to type in the cast) because when you
upcast you're implicitly restricting the number of methods you can invoke, as
opposed to downcasting, which implies that later on, you might want to invoke a
more specific method.
Implementation classes :
• Provide concrete (nonabstract) implementations for all methods from the
declared interface.
• Follow all the rules for legal overrides.
• Declare no checked exceptions on implementation methods other than those
declared by the interface method, or subclasses of those declared by the
interface method.
• Maintain the signature of the interface method, and maintain the same return
type (or a subtype). (But it does not have to declare the exceptions declared in
the interface method declaration.)
• An implementation class can itself be abstract! For example, the following is
legal for a class Ball implementing Bounceable:
abstract class Ball implements Bounceable { }
• A class can implement more than one interface. It's perfectly legal to say, for
example, the following:

public class Ball implements Bounceable, Serializable, Runnable { ... }
• An interface can itself extend another interface, but never implement anything.
The following code is perfectly legal:
public interface Bounceable extends Moveable { } // ok!
Implementation classes (contd … ):
• An interface can extend more than one interface! Think about that for a moment.
public class Programmer extends Employee, Geek { } // Illegal!
a class is not allowed to extend multiple classes in Java. An interface, however,
is free to extend multiple interfaces.
interface Bounceable extends Moveable, Spherical { }//Ok
•

Cannot implement a class.

• Interface can’t implement interface
• Interface can’t extend a class
• A class can’t extend multiple classes
• Class can implement multiple interfaces
• Interface can extend multiple interfaces
• A class can extend and implement at the same time.
class Yow extends Foo implements Fi
Ex : https://gist.github.com/rajeevprasanna/8501200
Legal return types
•

Return Types on Overloaded Methods : Remember that method overloading is not much
more than name reuse. The overloaded method is a completely different method from any
other method of the same name. So if you inherit a method but overload it in a subclass,
you're not subject to the restrictions of overriding, which means you can declare any return
type you like. What you can't do is change only the return type. To overload a method,
remember, you must change the argument list.
Ex : https://gist.github.com/rajeevprasanna/8501298

• Overriding and Return Types, and Covariant Returns : you're allowed to change the
return type in the overriding method as long as the new return type is a subtype of the declared
return type of the overridden (superclass) method.
Ex : https://gist.github.com/rajeevprasanna/8501351
Returning a value
 You can return null in a method with an object reference return type.
 An array is a perfectly legal return type.
 In a method with a primitive return type, you can return any value or variable that can be
implicitly converted to the declared return type.
 In a method with a primitive return type, you can return any value or

 variable that can be explicitly cast to the declared return type.
 You must not return anything from a method with a void return type.
 In a method with an object reference return type, you can return any object type that can be
implicitly cast to the declared return type.
Constructor and Instantiation
•

Every class including abstract classes, Must have a constructor.

•

Constructors are that they have no return type and their names must exactly match the class
name.

•

Constructors are used to initialize instance variable state
ex : https://gist.github.com/rajeevprasanna/8501958

•

It's very common (and desirable) for a class to have a no-arg constructor, regardless of how
many other overloaded constructors are in the class (yes, constructors can be overloaded).

•

Occasionally you have a class where it makes no sense to create an instance without
supplying information to the constructor.

•

Constructor Chaining : Every constructor invokes the constructor of its superclass with an
(implicit) call to super(), unless the constructor invokes an overloaded constructor of the same
class (more on that in a minute).
Ex : https://gist.github.com/rajeevprasanna/8502002
Rules for Constructors :
• Constructors can use any access modifier, including private. (A private
constructor means only code within the class itself can instantiate an object of
that type, so if the private constructor class wants to allow an instance of the
class to be used, the class must provide a static method or variable that allows
access to an instance created from within the class.)
• The constructor name must match the name of the class.
• Constructors must not have a return type.
• It's legal (but stupid) to have a method with the same name as the class, but that
doesn't make it a constructor. If you see a return type, it's a method rather than a
constructor. In fact, you could have both a method and a constructor with the
same name—the name of the class—in the same class, and that's not a problem
for Java. Be careful not to mistake a method for a constructor—be sure to look
for a return type.
• If you don't type a constructor into your class code, a default constructor will be
automatically generated by the compiler.
• The default constructor is ALWAYS a no-arg constructor.
• If you want a no-arg constructor and you've typed any other constructor(s) into
your class code, the compiler won't provide the no-arg constructor (or any other
constructor) for you. In other words, if you've typed in a construc- tor with
arguments, you won't have a no-arg constructor unless you type it in yourself!
Rules for Constructors (contd …):
• Every constructor has, as its first statement, either a call to an overloaded
constructor (this()) or a call to the superclass constructor (super()), although
remember that this call can be inserted by the compiler.
• If you do type in a constructor (as opposed to relying on the compiler-generated default constructor), and you do not type in the call to super() or a call to
this(), the compiler will insert a no-arg call to super() for you, as the very first
statement in the constructor.
• A call to super() can be either a no-arg call or can include arguments passed to
the super constructor.
• A no-arg constructor is not necessarily the default (i.e., compiler-supplied)
constructor, although the default constructor is always a no-arg constructor. The
default constructor is the one the compiler provides! While the default
constructor is always a no-arg constructor, you're free to put in your own no- arg
constructor.
• You cannot make a call to an instance method, or access an instance variable,
until after the super constructor runs.
• Only static variables and methods can be accessed as part of the call to su- per()
or this(). (Example: super(Animal.NAME) is OK, because NAME is declared as
a static variable.)
Rules for Constructors (contd …) :
• Abstract classes have constructors, and those constructors are always called
when a concrete subclass is instantiated.
• Interfaces do not have constructors. Interfaces are not part of an object's
inheritance tree.

• The only way a constructor can be invoked is from within another construc- tor.
In other words, you can't write code that actually calls a constructor as follows:
class Horse {
Horse() { } // constructor
void doStuff() { Horse(); // calling the constructor - illegal!
}
}
• The compiler will generate a default constructor for a class, if the class doesn't
have any constructors defined.

• Default constructor :
•
•
•

The default constructor has the same access modifier as the class.
The default constructor has no arguments.
The default constructor includes a no-arg call to the super constructor (super()).

• Super constructor with arguments : https://gist.github.com/rajeevprasanna/8502195
Java session2
Rules for Constructors :
• Constructors are never inherited. They aren't methods. They can't be overridden
(because they aren't methods and only instance methods can be overridden)
• Although constructors can't be overridden, you've already seen that they can be
overloaded.
• Overloading a constructor means typing in multiple versions of the constructor,
each having a different argument list.
• Overloading a constructor is typically used to provide alternate ways for clients
to instantiate objects of your class.
• Key Rule: The first line in a constructor must be a call to super() or a call to
this().
• No exceptions. If you have neither of those calls in your constructor, the
compiler will insert the no-arg call to super(). In other words, if constructor A()
has a call to this(), the compiler knows that constructor A() will not be the one to
invoke super().
• The preceding rule means a constructor can never have both a call to super() and
a call to this(). Because each of those calls must be the first statement in a
constructor, you can't legally use both in the same constructor. That also means
the compiler will not put a call to super() in any constructor that has a call to
this().
• Ex : https://gist.github.com/rajeevprasanna/8502254

More Related Content

What's hot (20)

TXT
Java interview
Mohammad Shahban
 
PDF
Object oriented programming
mustafa sarac
 
PPTX
chap 6 : Objects and classes (scjp/ocjp)
It Academy
 
PPTX
Java basics
Shivanshu Purwar
 
PPT
Unit 3 Java
arnold 7490
 
PPTX
Introduction to OOP(in java) BY Govind Singh
prabhat engineering college
 
DOCX
Viva file
anupamasingh87
 
DOC
C#
LiquidHub
 
PPT
11 advance inheritance_concepts
Arriz San Juan
 
PPT
Unit 4 Java
arnold 7490
 
PPTX
Java interview questions 2
Sherihan Anver
 
DOC
Java interview questions
G C Reddy Technologies
 
PPT
Oops Concept Java
Kamlesh Singh
 
PPTX
Suga java training_with_footer
Sugavanam Natarajan
 
DOC
116824015 java-j2 ee
homeworkping9
 
PPTX
Polymorphism in java
Elizabeth alexander
 
PPTX
Local variables Instance variables Class/static variables
Sohanur63
 
PPTX
Object oriented programming in java
Elizabeth alexander
 
PPTX
oops concept in java | object oriented programming in java
CPD INDIA
 
ODP
Beginners Guide to Object Orientation in PHP
Rick Ogden
 
Java interview
Mohammad Shahban
 
Object oriented programming
mustafa sarac
 
chap 6 : Objects and classes (scjp/ocjp)
It Academy
 
Java basics
Shivanshu Purwar
 
Unit 3 Java
arnold 7490
 
Introduction to OOP(in java) BY Govind Singh
prabhat engineering college
 
Viva file
anupamasingh87
 
11 advance inheritance_concepts
Arriz San Juan
 
Unit 4 Java
arnold 7490
 
Java interview questions 2
Sherihan Anver
 
Java interview questions
G C Reddy Technologies
 
Oops Concept Java
Kamlesh Singh
 
Suga java training_with_footer
Sugavanam Natarajan
 
116824015 java-j2 ee
homeworkping9
 
Polymorphism in java
Elizabeth alexander
 
Local variables Instance variables Class/static variables
Sohanur63
 
Object oriented programming in java
Elizabeth alexander
 
oops concept in java | object oriented programming in java
CPD INDIA
 
Beginners Guide to Object Orientation in PHP
Rick Ogden
 

Similar to Java session2 (20)

PPTX
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
VinishA23
 
PDF
JAVA-PPT'S.pdf
AnmolVerma363503
 
PDF
Unit 2
Amar Jukuntla
 
PPTX
Java chapter 5
Abdii Rashid
 
PPTX
JAVA-PPT'S-complete-chrome.pptx
KunalYadav65140
 
PPTX
JAVA-PPT'S.pptx
RaazIndia
 
PPTX
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
mohanrajm63
 
PDF
Java/J2EE interview Qestions
Arun Vasanth
 
PDF
OOPs Concepts - Android Programming
Purvik Rana
 
PPTX
Introduction to OOPs second year cse.pptx
solemanhldr
 
PPTX
Core java oop
Parth Shah
 
PPT
L7 inheritance
teach4uin
 
PPT
L7 inheritance
teach4uin
 
DOCX
JAVA Notes - All major concepts covered with examples
Sunil Kumar Gunasekaran
 
PPTX
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
PPTX
SKILLWISE - OOPS CONCEPT
Skillwise Group
 
PPT
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
PPTX
Inheritance.pptx
Karthik Rohan
 
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
VinishA23
 
JAVA-PPT'S.pdf
AnmolVerma363503
 
Java chapter 5
Abdii Rashid
 
JAVA-PPT'S-complete-chrome.pptx
KunalYadav65140
 
JAVA-PPT'S.pptx
RaazIndia
 
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
mohanrajm63
 
Java/J2EE interview Qestions
Arun Vasanth
 
OOPs Concepts - Android Programming
Purvik Rana
 
Introduction to OOPs second year cse.pptx
solemanhldr
 
Core java oop
Parth Shah
 
L7 inheritance
teach4uin
 
L7 inheritance
teach4uin
 
JAVA Notes - All major concepts covered with examples
Sunil Kumar Gunasekaran
 
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
SKILLWISE - OOPS CONCEPT
Skillwise Group
 
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
Inheritance.pptx
Karthik Rohan
 
Ad

More from Rajeev Kumar (9)

PDF
Db performance optimization with indexing
Rajeev Kumar
 
PPTX
Javasession10
Rajeev Kumar
 
PPT
Jms intro
Rajeev Kumar
 
PPTX
Javasession8
Rajeev Kumar
 
PPTX
Javasession6
Rajeev Kumar
 
PPTX
Javasession7
Rajeev Kumar
 
PPTX
Javasession5
Rajeev Kumar
 
PPTX
Javasession4
Rajeev Kumar
 
PDF
Java session 3
Rajeev Kumar
 
Db performance optimization with indexing
Rajeev Kumar
 
Javasession10
Rajeev Kumar
 
Jms intro
Rajeev Kumar
 
Javasession8
Rajeev Kumar
 
Javasession6
Rajeev Kumar
 
Javasession7
Rajeev Kumar
 
Javasession5
Rajeev Kumar
 
Javasession4
Rajeev Kumar
 
Java session 3
Rajeev Kumar
 
Ad

Recently uploaded (20)

PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PPTX
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
Introduction to Indian Writing in English
Trushali Dodiya
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Difference between write and update in odoo 18
Celine George
 
Introduction presentation of the patentbutler tool
MIPLM
 
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 

Java session2

  • 2. Object Orientation • Class • Object • Encapsulation • Inheritance • Polymorphism • Abstraction • Overriding and overloading • Reference variable casting • Legal return types • Constructors and instantiation
  • 3. OOP
  • 4.  Class : A class can be defined as a template/blue print that describes the behaviors/states that object of its type support. Ex : http://ideone.com/kBqxR1 Object : Objects have states and behaviors. It is an instance of a class. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. Refer example : http://ideone.com/FBN06D Refer docs : http://docs.oracle.com/javase/tutorial/java/concepts/object.html
  • 5. Object creation  Using new keyword : Most common way to create object. Detect errors like class not found at compile time. TestObject object = new TestObject()  Using Class. forName() : Useful if we have class name with default constructor TestObject object =(TestObject)Class.forName(“package.TestObject”).newInstance()  Using Clone() : Used for creating copy of an existing object TestObject originalObject = new TestObject(); TestObject cloneObject = originalObject.clone();  Using object deserialization : Useful for creating object from serialized form ObjectInputStream inputStream = new ObjectInputStream(anInputStream); TestObject object = (TestObject)inputStream.readObject(); Refer example here : https://gist.github.com/rajeevprasanna/8493409
  • 6. • Variable types or blocks. They Local variables : Variables defined inside methods, constructors declared and initialized within the method and destroyed after method execution. cannot use access modifier for local variables. No default value. Should be declared and initialized before first use. Implemented at Stack level. • Instance variables : Declared within a class but outside any method. These are initialized when class is created and lives till the object is destroyed. When a space is created for an object in the heap, a slot for each instance variable value is created Prefer declaring variable as instance variables only if they are used at more than one method, constructor or block They have access modifiers and visible across the whole class and initialized to default values for numbers default is 0, for Boolean default is false, for object reference it is null. • Class Variables : similar to instance variables with static modifier Static variables are stored in static memory. One copy is shared across all instances. Make them final to avoid getting modified by any one during life cycle as it last for entire program
  • 7. Encapsulation  Encapsulation is the ability to package data, related behavior in an object bundle and controls/restrict access to them from other objects. It is all about packaging related stuff together and hide them from external elements.  Encapsulation is not all about data hiding only. It is all about grouping or packaging related data and behavior.  Primary benefit of encapsulation is better maintainability. It gives total control over class fields to the class. Also users will not aware of internal implementations. Better ways to encapsulate object :  Keep instance variables protected(with an access modifier, often private)  Make public accessor methods, and force calling code to use those methods rather than directly accessing the instance variables.  For the methods, use the JavaBeans naming convention of ser<somePropertyName> and get<somePropertyName> Refer examples here : https://gist.github.com/rajeevprasanna/8494434
  • 8. Inheritance  IS-A relationship is-a relationship is totally based on inheritance which can be class type or interface inheritance ex: it is like saying “A is a B type of thing”. Apple is a fruit, car is a vehicle Inheritance is a unidirectional. Ex : House is a building but building is not a house. we can say is-a relationship if it uses extends or implements keyword. Tightly coupled ex : https://gist.github.com/rajeevprasanna/8499616 https://gist.github.com/rajeevprasanna/8500052  HAS-A relationship(Composition relationship) composition or has-A relationship means use of instance variables that are reference to other objects. Composition is dynamic binding (run time binding) while Inheritance is static binding (compile time binding) . It is loosely coupled. ex : https://gist.github.com/rajeevprasanna/8499902 https://gist.github.com/rajeevprasanna/8500118  InstanceOf : https://gist.github.com/rajeevprasanna/8499735
  • 9. Inheritance… Two most common reasons to use inheritance are : • To promote code reuse ex : https://gist.github.com/rajeevprasanna/8499902 • To use polymorphism ex : https://gist.github.com/rajeevprasanna/8499990 Check differences here : http://guruzon.com/1/oop-concepts/inheritance-andcomposition/difference-between-is-a-and-has-a-relationships-tutorial-example
  • 10. Polymorphism • Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. • Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object. • Only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed. • The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object • A reference variable can refer to any object of the same type as the declared reference, or— this is the big one—it can refer to any subtype of the declared type! • A reference variable can be declared as a class type or an interface type. If the variable is declared as an interface type, it can reference any object of any class that implements the interface. • A class cannot extend more than one class. That means one parent per class. Any given class might have multiple classes up its inheritance tree, but that's not the same as saying a class directly extends two classes. Ex : https://gist.github.com/rajeevprasanna/8500554
  • 11. Polymorphism types… • Polymorphism allows you define a Super type and have multiple subtype implementations • Polymorphism is of two types : 1. Compile time or static polymorphism 2. Runtime or dynamic polymorphism • Compile time polymorphism : Method overloading is a compile time polymorphism As we can have multiple subtype implementations for a super type, the compiler determines which type to be invoked at the compile time. ex : https://gist.github.com/rajeevprasanna/8500616 • Runtime polymorphism : Method overriding is a runtime polymorphism. As we can have multiple subtype implementations for a super type, Java virtual machine determines the proper type to be invoked at the runtime. Ex : https://gist.github.com/rajeevprasanna/8500647
  • 12. Overriding method rules : • The argument list must exactly match that of the overridden method. If they don't match, you can end up with an overloaded method you didn't intend • The return type must be the same as, or a subtype of, the return type declared in the original overridden method in the superclass. (More on this in a few pages when we discuss covariant returns.) • The access level can't be more restrictive than the overridden method's. • The access level CAN be less restrictive than that of the overridden method. • Instance methods can be overridden only if they are inherited by the subclass. A subclass within the same package as the instance's superclass can override any superclass method that is not marked private or final. A subclass in a different package can override only those non-final methods marked pub- lic or protected (since protected methods are inherited by the subclass). • The overriding method CAN throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception. • The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException.
  • 13. Overriding method rules (contd … ): • The overriding method can throw narrower or fewer exceptions. Just because an overridden method "takes risks" doesn't mean that the overriding subclass' exception takes the same risks. Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of what the overridden method declares. • You cannot override a method marked final. • You cannot override a method marked static. • If a method can't be inherited, you cannot override it. Remember that overriding implies that you're reimplementing a method you inherited!  Superclass method invoker : https://gist.github.com/rajeevprasanna/8500736 • If a method is overridden but you use a polymorphic (supertype) reference to refer to the subtype object with the overriding method, the compiler assumes you’re calling the supertype version of the method. If the supertype version declares a checked exception, but the overriding subtype method does not, the compiler still thinks you are calling a method that declares an exception. ex : https://gist.github.com/rajeevprasanna/8500769
  • 14. Examples of Legal and Illegal Method Overrides(for the above example) :
  • 15. Polymorphism in Overloaded and Overridden Methods: • • polymorphism doesn't determine which overloaded version is called; polymorphism does come into play when the decision is about which overridden version of a method is called. Ex with both overloading and overriding : https://gist.github.com/rajeevprasanna/8500851 • We can overload a method without overriding in subclass. Ex : https://gist.github.com/rajeevprasanna/8500874
  • 16. Differences Between Overloaded and Overridden Methods : Check covarient explanation here : https://blogs.oracle.com/sundararajan/entry/covariant_return_types_in_java
  • 17. Reference variable casting  Upcasting  Downcasting • Animal animal = new Dog(); But what happens when you want to use that animal reference variable to invoke a method that only class Dog has? ex : https://gist.github.com/rajeevprasanna/8501055 • Unlike downcasting, upcasting (casting up the inheritance tree to a more general type) works implicitly (i.e., you don't have to type in the cast) because when you upcast you're implicitly restricting the number of methods you can invoke, as opposed to downcasting, which implies that later on, you might want to invoke a more specific method.
  • 18. Implementation classes : • Provide concrete (nonabstract) implementations for all methods from the declared interface. • Follow all the rules for legal overrides. • Declare no checked exceptions on implementation methods other than those declared by the interface method, or subclasses of those declared by the interface method. • Maintain the signature of the interface method, and maintain the same return type (or a subtype). (But it does not have to declare the exceptions declared in the interface method declaration.) • An implementation class can itself be abstract! For example, the following is legal for a class Ball implementing Bounceable: abstract class Ball implements Bounceable { } • A class can implement more than one interface. It's perfectly legal to say, for example, the following: public class Ball implements Bounceable, Serializable, Runnable { ... } • An interface can itself extend another interface, but never implement anything. The following code is perfectly legal: public interface Bounceable extends Moveable { } // ok!
  • 19. Implementation classes (contd … ): • An interface can extend more than one interface! Think about that for a moment. public class Programmer extends Employee, Geek { } // Illegal! a class is not allowed to extend multiple classes in Java. An interface, however, is free to extend multiple interfaces. interface Bounceable extends Moveable, Spherical { }//Ok • Cannot implement a class. • Interface can’t implement interface • Interface can’t extend a class • A class can’t extend multiple classes • Class can implement multiple interfaces • Interface can extend multiple interfaces • A class can extend and implement at the same time. class Yow extends Foo implements Fi Ex : https://gist.github.com/rajeevprasanna/8501200
  • 20. Legal return types • Return Types on Overloaded Methods : Remember that method overloading is not much more than name reuse. The overloaded method is a completely different method from any other method of the same name. So if you inherit a method but overload it in a subclass, you're not subject to the restrictions of overriding, which means you can declare any return type you like. What you can't do is change only the return type. To overload a method, remember, you must change the argument list. Ex : https://gist.github.com/rajeevprasanna/8501298 • Overriding and Return Types, and Covariant Returns : you're allowed to change the return type in the overriding method as long as the new return type is a subtype of the declared return type of the overridden (superclass) method. Ex : https://gist.github.com/rajeevprasanna/8501351
  • 21. Returning a value  You can return null in a method with an object reference return type.  An array is a perfectly legal return type.  In a method with a primitive return type, you can return any value or variable that can be implicitly converted to the declared return type.  In a method with a primitive return type, you can return any value or  variable that can be explicitly cast to the declared return type.  You must not return anything from a method with a void return type.  In a method with an object reference return type, you can return any object type that can be implicitly cast to the declared return type.
  • 22. Constructor and Instantiation • Every class including abstract classes, Must have a constructor. • Constructors are that they have no return type and their names must exactly match the class name. • Constructors are used to initialize instance variable state ex : https://gist.github.com/rajeevprasanna/8501958 • It's very common (and desirable) for a class to have a no-arg constructor, regardless of how many other overloaded constructors are in the class (yes, constructors can be overloaded). • Occasionally you have a class where it makes no sense to create an instance without supplying information to the constructor. • Constructor Chaining : Every constructor invokes the constructor of its superclass with an (implicit) call to super(), unless the constructor invokes an overloaded constructor of the same class (more on that in a minute). Ex : https://gist.github.com/rajeevprasanna/8502002
  • 23. Rules for Constructors : • Constructors can use any access modifier, including private. (A private constructor means only code within the class itself can instantiate an object of that type, so if the private constructor class wants to allow an instance of the class to be used, the class must provide a static method or variable that allows access to an instance created from within the class.) • The constructor name must match the name of the class. • Constructors must not have a return type. • It's legal (but stupid) to have a method with the same name as the class, but that doesn't make it a constructor. If you see a return type, it's a method rather than a constructor. In fact, you could have both a method and a constructor with the same name—the name of the class—in the same class, and that's not a problem for Java. Be careful not to mistake a method for a constructor—be sure to look for a return type. • If you don't type a constructor into your class code, a default constructor will be automatically generated by the compiler. • The default constructor is ALWAYS a no-arg constructor. • If you want a no-arg constructor and you've typed any other constructor(s) into your class code, the compiler won't provide the no-arg constructor (or any other constructor) for you. In other words, if you've typed in a construc- tor with arguments, you won't have a no-arg constructor unless you type it in yourself!
  • 24. Rules for Constructors (contd …): • Every constructor has, as its first statement, either a call to an overloaded constructor (this()) or a call to the superclass constructor (super()), although remember that this call can be inserted by the compiler. • If you do type in a constructor (as opposed to relying on the compiler-generated default constructor), and you do not type in the call to super() or a call to this(), the compiler will insert a no-arg call to super() for you, as the very first statement in the constructor. • A call to super() can be either a no-arg call or can include arguments passed to the super constructor. • A no-arg constructor is not necessarily the default (i.e., compiler-supplied) constructor, although the default constructor is always a no-arg constructor. The default constructor is the one the compiler provides! While the default constructor is always a no-arg constructor, you're free to put in your own no- arg constructor. • You cannot make a call to an instance method, or access an instance variable, until after the super constructor runs. • Only static variables and methods can be accessed as part of the call to su- per() or this(). (Example: super(Animal.NAME) is OK, because NAME is declared as a static variable.)
  • 25. Rules for Constructors (contd …) : • Abstract classes have constructors, and those constructors are always called when a concrete subclass is instantiated. • Interfaces do not have constructors. Interfaces are not part of an object's inheritance tree. • The only way a constructor can be invoked is from within another construc- tor. In other words, you can't write code that actually calls a constructor as follows: class Horse { Horse() { } // constructor void doStuff() { Horse(); // calling the constructor - illegal! } } • The compiler will generate a default constructor for a class, if the class doesn't have any constructors defined. • Default constructor : • • • The default constructor has the same access modifier as the class. The default constructor has no arguments. The default constructor includes a no-arg call to the super constructor (super()). • Super constructor with arguments : https://gist.github.com/rajeevprasanna/8502195
  • 27. Rules for Constructors : • Constructors are never inherited. They aren't methods. They can't be overridden (because they aren't methods and only instance methods can be overridden) • Although constructors can't be overridden, you've already seen that they can be overloaded. • Overloading a constructor means typing in multiple versions of the constructor, each having a different argument list. • Overloading a constructor is typically used to provide alternate ways for clients to instantiate objects of your class. • Key Rule: The first line in a constructor must be a call to super() or a call to this(). • No exceptions. If you have neither of those calls in your constructor, the compiler will insert the no-arg call to super(). In other words, if constructor A() has a call to this(), the compiler knows that constructor A() will not be the one to invoke super(). • The preceding rule means a constructor can never have both a call to super() and a call to this(). Because each of those calls must be the first statement in a constructor, you can't legally use both in the same constructor. That also means the compiler will not put a call to super() in any constructor that has a call to this(). • Ex : https://gist.github.com/rajeevprasanna/8502254