SlideShare a Scribd company logo
CHAPTER 8
Classes and
Objects in Java
PART 2
1
Presentedby NuzhatMemon
╸ VariableTypes
╸ Inheritance
╸ Polymorphism& typesof polymorphism
╸ methodoverloading andmethodoverridden
╸ Access Modifiersin Packages
╸ CompositionandAggregation
2
AGENDA
Presentedby NuzhatMemon 3
VARIABLE TYPES
int age=15;
float pi=3.14;
static int count=0;
void display(){
int total=50;
}
Instance variables
local variable
Class variable
int age=15;
variable
value
Presentedby NuzhatMemon 4
Instance variables Class variables Local variables
It definedwithinaclassbut
outsideanymethod.
It definedinaclass,outsideany
method,withthe ‘static’ keyword.
It definesinsidemethodsor
blocks.
Formal parameterofthe methods
arealsolocalvariable.
Thesevariablesareallocated
memoryfromheapareawhenan
objectiscreated.
These variablesareallocated
memoryonlyonceperclassand is
sharedby allitsobject.
Theyarecreatedwhenthe method
orblock isstartedand destroyed
whenthe method orblock has
completed.
Initialized withdefaultvalues. Initialized withdefaultvalues. Notinitializedby defaultvalues.
class demo{
void method1 (int n) {
int a;
//code
}
}
int age=15;
float pi=3.14;
void display(){
//code
}
<objectname>.<variable/method>
static int count=0;
void display(){
int total=50;
}
<classname>.<classvariable/class
method>
classVar
Instance
Var
Instance
Var
Obj1 Obj2
Presentedby NuzhatMemon
• Providereusabilityfeature.
• Allowsustobuildnewclasswithaddedcapabilitiesby extending existing
class.
• Inheritancemodels ‘is a’ relationshipbetweentwo classes.forexample,
classroomisa room,studentisa person.
• Hereroomand personarecalledparentclassand classroomand student
arecalledchild classes
• Commonfeaturesarekeptin superclass
• A subclassinheritsallinstancevariablesandmethodsfromsuperclass
and itmay haveitsownaddedvariablesandmethods.
• A subclassis nota subsetof superclass.In fact,subclassusuallycontains
moreinformationandmethod than itssuperclass.
5
Super class or
Base class
Parent Class
Sub class or
Derived class or
Extended class
Child Class
Call, SMS, Camera, Music
call, SMS, Music, Camera
INHERITANCE
GPS, Video call
Presentedby NuzhatMemon
• In Java,we can havedifferent methods; when multiple methods having
same method name but a different signature in a class is known as
‘method overloading’.
• The method’s signature is a combination ofthe method name, the typeof
return value, alist ofparameters.
• For example, tofindmaximum oftwointegers, maximum of three integers,
maximum oftwodouble numbers andsoon. Here, one requires to
perform similar task but on different set of numbers.
• Method overloading is alsoknown as “polymorphism”.Because
polymorphism means “many forms”
• In such scenario, javafacilitates tocreate methods with same name but
different parameters.
6
Polymorphism
many forms
POLYMORPHISM (Method Overloading)
class Test{
void max(int a,int b)
void max(int a, int b,int c)
void max(doublea, doubleb)
}
Presentedby NuzhatMemon 7
• Whensuperclass and subclass havemethods with same signature, a superclass method is said to
beoverridden inthe subclass.
• Whensuch method of superclass is to referred, weneed to use keyword‘super’ with dot
operator and method name.
• Private members of a superclass is not visible to subclass
• Protected members are available as private memberin theinherited subclass.
OVERRIDDEN METHOD
void display(){}
void display(){}
Presentedby NuzhatMemon
VISIBILITY MODIFIERS FOR ACCESS CONTROL
• Access control is about controlling visibility. Access modifiers areknown as visibility modifiers.
• Toprotect a method orvariable, weuse the four levels of visibility toprovidenecessary protection.
• The four P’s ofprotection arepublic, package, protected andprivate.
8
• When no modifier is used, it is the default one having visibility only within a package that contains the
class
• Package is used toorganize classes.
• Package statement should beadded as the firstnon-comment ornon-blank line in the source file.
• When afile does not have package statement, the classes defined in the file areplaced in default package.
• Syntax of package statement:
package <packagename>;
Package
Presentedby NuzhatMemon
VISIBILITY MODIFIERS OR ACCESS MODIFIER
9
LEVEL
OF
ACCESS
MODIFIER
DESCRIPTION
VISIBILITY
Class Other classin
samepackage
Subclass
World
1ST
PUBLIC widestpossibleaccess
2ND
PACKAGE
[No Modifier
No precise name]
defaultlevel of protection.
Narrowerthan publicvariables
3RD
PROTECTED
narrowerthanpublicand package,
but widerthan fullprivacy provided
by fourthlevelprivate
4TH
PRIVATE the narrowestvisibility
Presentedby NuzhatMemon
4 P’s
11
Public Package Protected Private
1st level of access. 2nd level of access thathas
noprecise name.
3rd level ofaccess. 4th level ofaccess and
Highest level of protection
possible.
This is thewidest possible access. This is thedefault level of
protection. Thescope is
narrowerthan public
variables
Visibility is narrower than
two levels “public” and
“package”,butwider than
full privacy providedby
fourthlevel “private”.
Itprovides the narrowest
visibility.Private methods and
variables are directly
accessible onlyby themethods
defined within a class.
• Any method or variable is visible to
the class in which it is defined
• All the classes outside this class
• classes defined in other package
also.
• We have used publickeyword with
main() method tomake it visible
anywhere.
Thevariable or methodcan
be accessed from
anywhere in thepackage
that contains the class, but
notaccess fromoutside
that package.
This level ofprotection is
sued toallow access only to
subclass orto share with
the methods declared as
“friend”.
They cannot be seen by any
otherclass. Itprovides data
encapsulation.
Presentedby NuzhatMemon
• Useof accessorand mutator methods willpreventthevariables from getting directly accessedand
modified by other usersof the class.
12
ACCESSOR AND MUTATOR METHODS
ACCESSOR MUTATOR
Allowprivatedatatobe usedby others,thenwrite Allowprivatedatatobe modifiedby others,then
Accessormethod istocapitalizethe firstletterof
firstletterofvariablename anduseprefixesget,
prefixesget,whichknown as“getter”.
Mutatormethod istocapitalizethe firstletterof
firstletterofvariablename anduseprefixesset,
prefixesset,whichknownas“setter”.
If wewantto allowothermethodsto readonly the
readonlythe datavalue,weshould use“getter”
use“getter”methods.
If wewantto allowothermethodsto modifythe data
modify thedata value,weshoulduse“setter”
use“setter”methods.
Presentedby NuzhatMemon
• Composition andaggregation arethe constructor ofclasses that incorporate other objects.
• They establish a “has a” relationship between classes.
13
LIBRARY ROOM
has a
COMPOSITION AND AGGREGATION
Person
• nm: Name
• addr: Address
• birthdate:date
• setbirthdate(d:int, m:int,
y:int):date
• display()
Name
• First Name: string
• Middle name:string
• last name:string
• fullName():string
• display()
Address
• house: string
• street:string
• state:string
• pincode:int
• fulladress(): string
• display()
Aclass ‘library’has a reading room. Here reading roomis an object ofthe class ‘Room’. Thus Libraryhas a room.
THANKS FOR
WATCHING 
PresentedbyNuzhatMemon

More Related Content

What's hot

What's hot (20)

java Method Overloading
java Method Overloadingjava Method Overloading
java Method Overloading
 
Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.net
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
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
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interface
 
Javapolymorphism
JavapolymorphismJavapolymorphism
Javapolymorphism
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and Polymorphism
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear
 
OOP java
OOP javaOOP java
OOP java
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
 
‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Hemajava
HemajavaHemajava
Hemajava
 

Similar to Std 12 computer chapter 8 classes and object in java (part 2)

Chapter 03 enscapsulation
Chapter 03 enscapsulationChapter 03 enscapsulation
Chapter 03 enscapsulation
Nurhanna Aziz
 
Complete java&j2ee
Complete java&j2eeComplete java&j2ee
Complete java&j2ee
Shiva Cse
 
Chapter 05 polymorphism extra
Chapter 05 polymorphism extraChapter 05 polymorphism extra
Chapter 05 polymorphism extra
Nurhanna Aziz
 

Similar to Std 12 computer chapter 8 classes and object in java (part 2) (20)

Chapter 03 enscapsulation
Chapter 03 enscapsulationChapter 03 enscapsulation
Chapter 03 enscapsulation
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 ee
 
Access Modifiers .pptx
Access Modifiers .pptxAccess Modifiers .pptx
Access Modifiers .pptx
 
Access Modifier.pptx
Access Modifier.pptxAccess Modifier.pptx
Access Modifier.pptx
 
Oops (inheritance&interface)
Oops (inheritance&interface)Oops (inheritance&interface)
Oops (inheritance&interface)
 
Master of Computer Application (MCA) – Semester 4 MC0078
Master of Computer Application (MCA) – Semester 4  MC0078Master of Computer Application (MCA) – Semester 4  MC0078
Master of Computer Application (MCA) – Semester 4 MC0078
 
chapter 5 concepts of object oriented programming
chapter 5 concepts of object oriented programmingchapter 5 concepts of object oriented programming
chapter 5 concepts of object oriented programming
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
 
Complete java&j2ee
Complete java&j2eeComplete java&j2ee
Complete java&j2ee
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Chapter 05 polymorphism extra
Chapter 05 polymorphism extraChapter 05 polymorphism extra
Chapter 05 polymorphism extra
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Chap1 packages
Chap1 packagesChap1 packages
Chap1 packages
 
Core java by amit
Core java by amitCore java by amit
Core java by amit
 
Oops abap fundamental
Oops abap fundamentalOops abap fundamental
Oops abap fundamental
 
Java presentation
Java presentationJava presentation
Java presentation
 

More from Nuzhat Memon

More from Nuzhat Memon (20)

Std 10 chapter 11 data type, expression and operators important MCQs
Std 10 chapter 11 data type, expression and operators important MCQsStd 10 chapter 11 data type, expression and operators important MCQs
Std 10 chapter 11 data type, expression and operators important MCQs
 
Std 10 Chapter 10 Introduction to C Language Important MCQs
Std 10 Chapter 10 Introduction to C Language Important MCQsStd 10 Chapter 10 Introduction to C Language Important MCQs
Std 10 Chapter 10 Introduction to C Language Important MCQs
 
Std 12 chapter 7 Java Basics Important MCQs
Std 12 chapter 7 Java Basics Important MCQsStd 12 chapter 7 Java Basics Important MCQs
Std 12 chapter 7 Java Basics Important MCQs
 
Std 12 computer chapter 8 classes and objects in java important MCQs
Std 12 computer chapter 8 classes and objects in java important MCQsStd 12 computer chapter 8 classes and objects in java important MCQs
Std 12 computer chapter 8 classes and objects in java important MCQs
 
Std 12 Computer Chapter 6 object oriented concept important mcqs
Std 12 Computer Chapter 6 object oriented concept important mcqsStd 12 Computer Chapter 6 object oriented concept important mcqs
Std 12 Computer Chapter 6 object oriented concept important mcqs
 
Std 12 computer chapter 6 object oriented concepts (part 1)
Std 12 computer chapter 6 object oriented concepts (part 1)Std 12 computer chapter 6 object oriented concepts (part 1)
Std 12 computer chapter 6 object oriented concepts (part 1)
 
Std 12 computer chapter 6 object oriented concepts (part 2)
Std 12 computer chapter 6 object oriented concepts (part 2)Std 12 computer chapter 6 object oriented concepts (part 2)
Std 12 computer chapter 6 object oriented concepts (part 2)
 
Std 12 computer java basics part 3 control structure
Std 12 computer java basics part 3 control structureStd 12 computer java basics part 3 control structure
Std 12 computer java basics part 3 control structure
 
Std 12 Computer Chapter 7 Java Basics (Part 2)
Std 12 Computer Chapter 7 Java Basics (Part 2)Std 12 Computer Chapter 7 Java Basics (Part 2)
Std 12 Computer Chapter 7 Java Basics (Part 2)
 
Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)
 
Std 12 Computer Chapter 13 other useful free tools and services important MCQs
Std 12 Computer Chapter 13 other useful free tools and services important MCQsStd 12 Computer Chapter 13 other useful free tools and services important MCQs
Std 12 Computer Chapter 13 other useful free tools and services important MCQs
 
Std 12 Computer Chapter 9 Working with Array and String in Java important MCQs
Std 12 Computer Chapter 9 Working with Array and String in Java important MCQsStd 12 Computer Chapter 9 Working with Array and String in Java important MCQs
Std 12 Computer Chapter 9 Working with Array and String in Java important MCQs
 
Std 10 computer chapter 10 introduction to c language (part2)
Std 10 computer chapter 10 introduction to c language (part2)Std 10 computer chapter 10 introduction to c language (part2)
Std 10 computer chapter 10 introduction to c language (part2)
 
Std 10 computer chapter 10 introduction to c language (part1)
Std 10 computer chapter 10 introduction to c language (part1)Std 10 computer chapter 10 introduction to c language (part1)
Std 10 computer chapter 10 introduction to c language (part1)
 
Std 10 computer chapter 9 Problems and Problem Solving
Std 10 computer chapter 9 Problems and Problem SolvingStd 10 computer chapter 9 Problems and Problem Solving
Std 10 computer chapter 9 Problems and Problem Solving
 
Std 11 Computer Chapter 5 Using Pictures in Synfig (Practical 3: Masking to R...
Std 11 Computer Chapter 5 Using Pictures in Synfig (Practical 3: Masking to R...Std 11 Computer Chapter 5 Using Pictures in Synfig (Practical 3: Masking to R...
Std 11 Computer Chapter 5 Using Pictures in Synfig (Practical 3: Masking to R...
 
Chapter 5 Using Pictures in Synfig (Practical 2: Masking to hide area in synfig)
Chapter 5 Using Pictures in Synfig (Practical 2: Masking to hide area in synfig)Chapter 5 Using Pictures in Synfig (Practical 2: Masking to hide area in synfig)
Chapter 5 Using Pictures in Synfig (Practical 2: Masking to hide area in synfig)
 
Std 11 Computer Chapter 5 Using Pictures in Synfig (Practical 1 Basics Opera...
Std 11 Computer Chapter 5 Using Pictures in Synfig (Practical 1  Basics Opera...Std 11 Computer Chapter 5 Using Pictures in Synfig (Practical 1  Basics Opera...
Std 11 Computer Chapter 5 Using Pictures in Synfig (Practical 1 Basics Opera...
 
Std 11 Computer Chapter 4 Introduction to Layers (Part 3 Solving Textual Exe...
Std 11 Computer Chapter 4 Introduction to Layers  (Part 3 Solving Textual Exe...Std 11 Computer Chapter 4 Introduction to Layers  (Part 3 Solving Textual Exe...
Std 11 Computer Chapter 4 Introduction to Layers (Part 3 Solving Textual Exe...
 
Std 11 Computer Chapter 4 Introduction to Layers (Part 2 Practical :Rotation ...
Std 11 Computer Chapter 4 Introduction to Layers (Part 2 Practical :Rotation ...Std 11 Computer Chapter 4 Introduction to Layers (Part 2 Practical :Rotation ...
Std 11 Computer Chapter 4 Introduction to Layers (Part 2 Practical :Rotation ...
 

Recently uploaded

plant breeding methods in asexually or clonally propagated crops
plant breeding methods in asexually or clonally propagated cropsplant breeding methods in asexually or clonally propagated crops
plant breeding methods in asexually or clonally propagated crops
parmarsneha2
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
YibeltalNibretu
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 

Recently uploaded (20)

How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
plant breeding methods in asexually or clonally propagated crops
plant breeding methods in asexually or clonally propagated cropsplant breeding methods in asexually or clonally propagated crops
plant breeding methods in asexually or clonally propagated crops
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
NLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptxNLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptx
 
B.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdfB.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Benefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational ResourcesBenefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational Resources
 

Std 12 computer chapter 8 classes and object in java (part 2)

  • 1. CHAPTER 8 Classes and Objects in Java PART 2 1
  • 2. Presentedby NuzhatMemon ╸ VariableTypes ╸ Inheritance ╸ Polymorphism& typesof polymorphism ╸ methodoverloading andmethodoverridden ╸ Access Modifiersin Packages ╸ CompositionandAggregation 2 AGENDA
  • 3. Presentedby NuzhatMemon 3 VARIABLE TYPES int age=15; float pi=3.14; static int count=0; void display(){ int total=50; } Instance variables local variable Class variable int age=15; variable value
  • 4. Presentedby NuzhatMemon 4 Instance variables Class variables Local variables It definedwithinaclassbut outsideanymethod. It definedinaclass,outsideany method,withthe ‘static’ keyword. It definesinsidemethodsor blocks. Formal parameterofthe methods arealsolocalvariable. Thesevariablesareallocated memoryfromheapareawhenan objectiscreated. These variablesareallocated memoryonlyonceperclassand is sharedby allitsobject. Theyarecreatedwhenthe method orblock isstartedand destroyed whenthe method orblock has completed. Initialized withdefaultvalues. Initialized withdefaultvalues. Notinitializedby defaultvalues. class demo{ void method1 (int n) { int a; //code } } int age=15; float pi=3.14; void display(){ //code } <objectname>.<variable/method> static int count=0; void display(){ int total=50; } <classname>.<classvariable/class method> classVar Instance Var Instance Var Obj1 Obj2
  • 5. Presentedby NuzhatMemon • Providereusabilityfeature. • Allowsustobuildnewclasswithaddedcapabilitiesby extending existing class. • Inheritancemodels ‘is a’ relationshipbetweentwo classes.forexample, classroomisa room,studentisa person. • Hereroomand personarecalledparentclassand classroomand student arecalledchild classes • Commonfeaturesarekeptin superclass • A subclassinheritsallinstancevariablesandmethodsfromsuperclass and itmay haveitsownaddedvariablesandmethods. • A subclassis nota subsetof superclass.In fact,subclassusuallycontains moreinformationandmethod than itssuperclass. 5 Super class or Base class Parent Class Sub class or Derived class or Extended class Child Class Call, SMS, Camera, Music call, SMS, Music, Camera INHERITANCE GPS, Video call
  • 6. Presentedby NuzhatMemon • In Java,we can havedifferent methods; when multiple methods having same method name but a different signature in a class is known as ‘method overloading’. • The method’s signature is a combination ofthe method name, the typeof return value, alist ofparameters. • For example, tofindmaximum oftwointegers, maximum of three integers, maximum oftwodouble numbers andsoon. Here, one requires to perform similar task but on different set of numbers. • Method overloading is alsoknown as “polymorphism”.Because polymorphism means “many forms” • In such scenario, javafacilitates tocreate methods with same name but different parameters. 6 Polymorphism many forms POLYMORPHISM (Method Overloading) class Test{ void max(int a,int b) void max(int a, int b,int c) void max(doublea, doubleb) }
  • 7. Presentedby NuzhatMemon 7 • Whensuperclass and subclass havemethods with same signature, a superclass method is said to beoverridden inthe subclass. • Whensuch method of superclass is to referred, weneed to use keyword‘super’ with dot operator and method name. • Private members of a superclass is not visible to subclass • Protected members are available as private memberin theinherited subclass. OVERRIDDEN METHOD void display(){} void display(){}
  • 8. Presentedby NuzhatMemon VISIBILITY MODIFIERS FOR ACCESS CONTROL • Access control is about controlling visibility. Access modifiers areknown as visibility modifiers. • Toprotect a method orvariable, weuse the four levels of visibility toprovidenecessary protection. • The four P’s ofprotection arepublic, package, protected andprivate. 8 • When no modifier is used, it is the default one having visibility only within a package that contains the class • Package is used toorganize classes. • Package statement should beadded as the firstnon-comment ornon-blank line in the source file. • When afile does not have package statement, the classes defined in the file areplaced in default package. • Syntax of package statement: package <packagename>; Package
  • 9. Presentedby NuzhatMemon VISIBILITY MODIFIERS OR ACCESS MODIFIER 9 LEVEL OF ACCESS MODIFIER DESCRIPTION VISIBILITY Class Other classin samepackage Subclass World 1ST PUBLIC widestpossibleaccess 2ND PACKAGE [No Modifier No precise name] defaultlevel of protection. Narrowerthan publicvariables 3RD PROTECTED narrowerthanpublicand package, but widerthan fullprivacy provided by fourthlevelprivate 4TH PRIVATE the narrowestvisibility
  • 10. Presentedby NuzhatMemon 4 P’s 11 Public Package Protected Private 1st level of access. 2nd level of access thathas noprecise name. 3rd level ofaccess. 4th level ofaccess and Highest level of protection possible. This is thewidest possible access. This is thedefault level of protection. Thescope is narrowerthan public variables Visibility is narrower than two levels “public” and “package”,butwider than full privacy providedby fourthlevel “private”. Itprovides the narrowest visibility.Private methods and variables are directly accessible onlyby themethods defined within a class. • Any method or variable is visible to the class in which it is defined • All the classes outside this class • classes defined in other package also. • We have used publickeyword with main() method tomake it visible anywhere. Thevariable or methodcan be accessed from anywhere in thepackage that contains the class, but notaccess fromoutside that package. This level ofprotection is sued toallow access only to subclass orto share with the methods declared as “friend”. They cannot be seen by any otherclass. Itprovides data encapsulation.
  • 11. Presentedby NuzhatMemon • Useof accessorand mutator methods willpreventthevariables from getting directly accessedand modified by other usersof the class. 12 ACCESSOR AND MUTATOR METHODS ACCESSOR MUTATOR Allowprivatedatatobe usedby others,thenwrite Allowprivatedatatobe modifiedby others,then Accessormethod istocapitalizethe firstletterof firstletterofvariablename anduseprefixesget, prefixesget,whichknown as“getter”. Mutatormethod istocapitalizethe firstletterof firstletterofvariablename anduseprefixesset, prefixesset,whichknownas“setter”. If wewantto allowothermethodsto readonly the readonlythe datavalue,weshould use“getter” use“getter”methods. If wewantto allowothermethodsto modifythe data modify thedata value,weshoulduse“setter” use“setter”methods.
  • 12. Presentedby NuzhatMemon • Composition andaggregation arethe constructor ofclasses that incorporate other objects. • They establish a “has a” relationship between classes. 13 LIBRARY ROOM has a COMPOSITION AND AGGREGATION Person • nm: Name • addr: Address • birthdate:date • setbirthdate(d:int, m:int, y:int):date • display() Name • First Name: string • Middle name:string • last name:string • fullName():string • display() Address • house: string • street:string • state:string • pincode:int • fulladress(): string • display() Aclass ‘library’has a reading room. Here reading roomis an object ofthe class ‘Room’. Thus Libraryhas a room.

Editor's Notes

  1. Constructor, private variable and method
  2. Same method name but differ in arguments  A milk at the same time can have different characteristic. Like a milk at the same time is a cheese, a yoghurt, an icecrem. So the same person posses different behavior in different situations. This is called polymorphism.