Std 12 computer chapter 8 classes and objects in java (Part 2) by Nuzhat Memon
Variable Type (Instance Variable, Class Variable, Local Variable)
Accessing an instance variable and method using Dot notation
Accessing class variable and method using class name
Inheritance
Polymorphism (Method overloading and Method overridden)
Access Modifier or Visibility Modifier in java (4 p's Public Package Private and Private)
Accessor and Mutator
Composition and Aggregation
Constructor (special kind of method called automatically when a new object is created)
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.
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.