SlideShare ist ein Scribd-Unternehmen logo
1 von 27
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
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

Weitere ähnliche Inhalte

Was ist angesagt?

Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingmustafa sarac
 
chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)It Academy
 
11 advance inheritance_concepts
11 advance inheritance_concepts11 advance inheritance_concepts
11 advance inheritance_conceptsArriz San Juan
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2Sherihan Anver
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 eehomeworkping9
 
Local variables Instance variables Class/static variables
Local variables Instance variables Class/static variablesLocal variables Instance variables Class/static variables
Local variables Instance variables Class/static variablesSohanur63
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Beginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPBeginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPRick Ogden
 

Was ist angesagt? (20)

Java interview
Java interviewJava interview
Java interview
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)
 
Java basics
Java basicsJava basics
Java basics
 
Unit 3 Java
Unit 3 JavaUnit 3 Java
Unit 3 Java
 
Introduction to OOP(in java) BY Govind Singh
Introduction to OOP(in java)  BY Govind SinghIntroduction to OOP(in java)  BY Govind Singh
Introduction to OOP(in java) BY Govind Singh
 
Viva file
Viva fileViva file
Viva file
 
C#
C#C#
C#
 
11 advance inheritance_concepts
11 advance inheritance_concepts11 advance inheritance_concepts
11 advance inheritance_concepts
 
Unit 4 Java
Unit 4 JavaUnit 4 Java
Unit 4 Java
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Oops Concept Java
Oops Concept JavaOops Concept Java
Oops Concept Java
 
Suga java training_with_footer
Suga java training_with_footerSuga java training_with_footer
Suga java training_with_footer
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 ee
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Local variables Instance variables Class/static variables
Local variables Instance variables Class/static variablesLocal variables Instance variables Class/static variables
Local variables Instance variables Class/static variables
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Beginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPBeginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHP
 

Ähnlich wie Java session2

Ähnlich wie Java session2 (20)

Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Learn java objects inheritance-overriding-polymorphism
Learn java objects  inheritance-overriding-polymorphismLearn java objects  inheritance-overriding-polymorphism
Learn java objects inheritance-overriding-polymorphism
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
Complete java&j2ee
Complete java&j2eeComplete java&j2ee
Complete java&j2ee
 
Object Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and InterfacesObject Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and Interfaces
 
Java
JavaJava
Java
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
 
Chapter 9 java
Chapter 9 javaChapter 9 java
Chapter 9 java
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptx
 
Java defining classes
Java defining classes Java defining classes
Java defining classes
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Review oop and ood
Review oop and oodReview oop and ood
Review oop and ood
 

Mehr von Rajeev Kumar

Mehr von Rajeev Kumar (9)

Db performance optimization with indexing
Db performance optimization with indexingDb performance optimization with indexing
Db performance optimization with indexing
 
Javasession10
Javasession10Javasession10
Javasession10
 
Jms intro
Jms introJms intro
Jms intro
 
Javasession8
Javasession8Javasession8
Javasession8
 
Javasession6
Javasession6Javasession6
Javasession6
 
Javasession7
Javasession7Javasession7
Javasession7
 
Javasession5
Javasession5Javasession5
Javasession5
 
Javasession4
Javasession4Javasession4
Javasession4
 
Java session 3
Java session 3Java session 3
Java session 3
 

Kürzlich hochgeladen

The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsRommel Regala
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
EMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxEMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxElton John Embodo
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxruthvilladarez
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 

Kürzlich hochgeladen (20)

The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World Politics
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
EMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxEMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 

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
  • 26.
  • 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