SlideShare a Scribd company logo
1 of 11
1. Start a newandroidproject
2. SelectEmptyactivity
3. Setthe name andpackage name andlocation
 Package name includesDomainname andcompanyname anddepartmentetc.
4. In Projectpanel rightclickonapp folderthenselectnew module
5. SelectJavaor KotlinLibrary
6. Setthe libraryname andclassname
7. You can see the package folders
 MainActivity.javaisin“oopapps”folder
 Person.javaisin“mylib”folder
 WhenyoubuildyourprojectAndroidStudiomakesafoldercalledbuildinmylibfolder
inside thatislibsfolderand mylib.jarisinside that.
 You can use mylib.jarinotherprojectlike .dll classlibraryinvisual studio.
Java Classes/Objects
Java isan object-orientedprogramminglanguage.
EverythinginJavaisassociatedwithclasses andobjects,alongwithitsattributesandmethods.For
example:inreal life,acar isan object.The car has attributes,suchasweightandcolor,and methods,
such as drive andbrake.
A Classislike anobjectconstructor,or a "blueprint"forcreating objects.
8. Insertsome code in MyPerson.class
 Line 1 : Indicatesthe package containingthe Javaclass.
 Line 3 : The publickeywordisan access modifier,meaningthatitisusedto setthe
access level forclasses.
We divide modifiersintotwogroups:
I. AccessModifiers - controlsthe accesslevel
II. Non-AccessModifiers - donotcontrol access level,butprovidesother
functionality
For classwe have 2 access modifier
I. Public: The classis accessible byanyotherclass
II. Default:The classis onlyaccessible by classesinthe same package.Thisis
usedwhenyoudon'tspecifyamodifier(like onlyclassPerson).
 Line 5, 6, 7 : we create some variable.
I. These variablesare private thatmeanstheyare accessible onlyinthisclass
II. Whenyoucreate a variable like “intnumber;”numberiszero but when you
create like this“Integernumber;”numberisnull.
Java Variables
Variablesare containersforstoringdatavalues.
In Java,there are differenttypesof variables,forexample:
String - storestext,suchas "Hello".Stringvaluesare surroundedbydouble quotes
int - storesintegers(whole numbers),withoutdecimals,suchas123 or -123
float - storesfloatingpointnumbers,withdecimals,suchas19.99 or -19.99
char - storessingle characters,suchas'a' or 'B'. Char valuesare surroundedbysingle quotes
boolean- storesvalueswithtwostates:true or false
9. Inside PersonclassblockrightclickandselectGenerate (Alt+Insert)
10. SelectConstructor
11. PressSelectNone button.
Java Constructors
A constructorin Javais a special methodthatisusedto initializeobjects.The constructoriscalledwhen
an objectof a classiscreated.It can be usedtoset initial valuesforobjectattributes.
Note that the constructorname must match the classname,and itcannot have a return type (like void).
Alsonote that the constructoris calledwhenthe objectiscreated.
All classeshave constructorsbydefault:if youdonot create a classconstructor yourself,Javacreates
one for you.However,thenyouare notable to setinitial valuesforobjectattributes.
Constructorscan alsotake parameters,whichisusedtoinitializeattributes.
12. Insertthiscode to Personclassconstructor:
13. In MainActivity.javafile,inOnCreate method type “MyPerson”thenpress(Alt+Enter)
14. SelectAdddependencyonmodule ‘mylib’thisjobaddsanotherbuild.gradle andmake all
dependencytoyourmodule.
15. In MainActivity.javafile,inOnCreate method rightclickon “MyPerson”then select“Show
ContextActions”
16. Select“ImportClass”
17. Insertcode like picture andrunproject
 Firstline createsmyPersonobjectfromMyPersonclass.
 Whenwe create an objectfrom a class,the constructor of the class isexecuted.
 Whenwe type “myPerson.”AndroidStudio offertoussome propertyandmethodbut
inthiscase we cannot see firstName orlastName andnationalIDbecause theyare
private.
 As youcan see inthe picture,the logisnotwhat I expected.Whatisthe solution?
 To answerthisquestion,we needto discussthe conceptof Encapsulation.
Encapsulation
The meaningof Encapsulation,istomake sure that "sensitive"dataishiddenfromusers.Toachieve
this,youmust:
declare classvariables/attributesasprivate
provide publicgetandsetmethodstoaccessand update the value of a private variable
Get and Set
We knowthatprivate variablescanonlybe accessedwithinthe same class(anoutside classhasno
access to it).However,itispossible toaccessthemif we provide publicgetandsetmethods.
The get methodreturnsthe variable value,andthe setmethodsetsthe value.
Syntax forboth isthat theystart witheithergetorset,followedbythe name of the variable,withthe
firstletterinuppercase.
Why Encapsulation?
 Bettercontrol of class attributesandmethods
 Classattributescanbe made read-only(if youonlyuse the getmethod),orwrite-only(ifyou
onlyuse the setmethod)
 Flexible:the programmercanchange one part of the code withoutaffectingotherparts
 Increasedsecurityof data
18. Go to MyPerson.classinsideclassblockpress(Alt+Enter),selectGetterandSetter
19. Selectall 3 variables
20. Nowchange Log in MainActivity.java
As youcan see,the outputiscorrect. If your logshowsa lot of data you can searchby tag inthis
case is“info”.
In the followingarticles,Iwill discussotherissuesof the object-orientedprogramminginAndroid
Studio.
In thisarticle,Iusedthe resourcesof the www.w3schools.com.
I will be happytoknowyour commentsandquestions.
Sayed Mahmood Ghaemmaghami

More Related Content

What's hot

Connecting Flash and Javascript using ExternalInterface
Connecting Flash and Javascript using ExternalInterfaceConnecting Flash and Javascript using ExternalInterface
Connecting Flash and Javascript using ExternalInterfaceBri Lance
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptForziatech
 
Future-proofing Your JavaScript Apps (Compact edition)
Future-proofing Your JavaScript Apps (Compact edition)Future-proofing Your JavaScript Apps (Compact edition)
Future-proofing Your JavaScript Apps (Compact edition)Addy Osmani
 

What's hot (7)

Connecting Flash and Javascript using ExternalInterface
Connecting Flash and Javascript using ExternalInterfaceConnecting Flash and Javascript using ExternalInterface
Connecting Flash and Javascript using ExternalInterface
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
Future-proofing Your JavaScript Apps (Compact edition)
Future-proofing Your JavaScript Apps (Compact edition)Future-proofing Your JavaScript Apps (Compact edition)
Future-proofing Your JavaScript Apps (Compact edition)
 
Js: master prototypes
Js: master prototypesJs: master prototypes
Js: master prototypes
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Prototype
PrototypePrototype
Prototype
 
Enterprise js pratices
Enterprise js praticesEnterprise js pratices
Enterprise js pratices
 

Similar to Object Oriented Programming in Android Studio

Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answersKrishnaov
 
Android App code starter
Android App code starterAndroid App code starter
Android App code starterFatimaYousif11
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptUsman Mehmood
 
Constructors in Java (2).pdf
Constructors in Java (2).pdfConstructors in Java (2).pdf
Constructors in Java (2).pdfkumari36
 
Object Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaObject Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaGaddafiAdamu1
 
Understanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneUnderstanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneDeepu S Nath
 
Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02Sopheak Sem
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design PatternsAddy Osmani
 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxDrYogeshDeshmukh1
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript Dhananjay Kumar
 
Unidad o informatica en ingles
Unidad o informatica en inglesUnidad o informatica en ingles
Unidad o informatica en inglesMarisa Torrecillas
 

Similar to Object Oriented Programming in Android Studio (20)

Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
 
Android App code starter
Android App code starterAndroid App code starter
Android App code starter
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
Constructors in Java (2).pdf
Constructors in Java (2).pdfConstructors in Java (2).pdf
Constructors in Java (2).pdf
 
Object Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaObject Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) java
 
Class 1 blog
Class 1 blogClass 1 blog
Class 1 blog
 
Understanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneUnderstanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG June
 
Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02
 
Ch2
Ch2Ch2
Ch2
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
C++ to java
C++ to javaC++ to java
C++ to java
 
Objective c
Objective cObjective c
Objective c
 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptx
 
ClassJS
ClassJSClassJS
ClassJS
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
OOP's Part 1
OOP's Part 1OOP's Part 1
OOP's Part 1
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
 
Unidad o informatica en ingles
Unidad o informatica en inglesUnidad o informatica en ingles
Unidad o informatica en ingles
 
Class 1
Class 1Class 1
Class 1
 

Recently uploaded

What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 

Recently uploaded (20)

What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 

Object Oriented Programming in Android Studio

  • 1. 1. Start a newandroidproject 2. SelectEmptyactivity 3. Setthe name andpackage name andlocation  Package name includesDomainname andcompanyname anddepartmentetc. 4. In Projectpanel rightclickonapp folderthenselectnew module
  • 3. 6. Setthe libraryname andclassname 7. You can see the package folders  MainActivity.javaisin“oopapps”folder  Person.javaisin“mylib”folder  WhenyoubuildyourprojectAndroidStudiomakesafoldercalledbuildinmylibfolder inside thatislibsfolderand mylib.jarisinside that.  You can use mylib.jarinotherprojectlike .dll classlibraryinvisual studio.
  • 4.
  • 5. Java Classes/Objects Java isan object-orientedprogramminglanguage. EverythinginJavaisassociatedwithclasses andobjects,alongwithitsattributesandmethods.For example:inreal life,acar isan object.The car has attributes,suchasweightandcolor,and methods, such as drive andbrake. A Classislike anobjectconstructor,or a "blueprint"forcreating objects. 8. Insertsome code in MyPerson.class  Line 1 : Indicatesthe package containingthe Javaclass.  Line 3 : The publickeywordisan access modifier,meaningthatitisusedto setthe access level forclasses. We divide modifiersintotwogroups: I. AccessModifiers - controlsthe accesslevel II. Non-AccessModifiers - donotcontrol access level,butprovidesother functionality For classwe have 2 access modifier I. Public: The classis accessible byanyotherclass II. Default:The classis onlyaccessible by classesinthe same package.Thisis usedwhenyoudon'tspecifyamodifier(like onlyclassPerson).  Line 5, 6, 7 : we create some variable. I. These variablesare private thatmeanstheyare accessible onlyinthisclass II. Whenyoucreate a variable like “intnumber;”numberiszero but when you create like this“Integernumber;”numberisnull.
  • 6. Java Variables Variablesare containersforstoringdatavalues. In Java,there are differenttypesof variables,forexample: String - storestext,suchas "Hello".Stringvaluesare surroundedbydouble quotes int - storesintegers(whole numbers),withoutdecimals,suchas123 or -123 float - storesfloatingpointnumbers,withdecimals,suchas19.99 or -19.99 char - storessingle characters,suchas'a' or 'B'. Char valuesare surroundedbysingle quotes boolean- storesvalueswithtwostates:true or false 9. Inside PersonclassblockrightclickandselectGenerate (Alt+Insert) 10. SelectConstructor 11. PressSelectNone button.
  • 7. Java Constructors A constructorin Javais a special methodthatisusedto initializeobjects.The constructoriscalledwhen an objectof a classiscreated.It can be usedtoset initial valuesforobjectattributes. Note that the constructorname must match the classname,and itcannot have a return type (like void). Alsonote that the constructoris calledwhenthe objectiscreated. All classeshave constructorsbydefault:if youdonot create a classconstructor yourself,Javacreates one for you.However,thenyouare notable to setinitial valuesforobjectattributes. Constructorscan alsotake parameters,whichisusedtoinitializeattributes.
  • 8. 12. Insertthiscode to Personclassconstructor: 13. In MainActivity.javafile,inOnCreate method type “MyPerson”thenpress(Alt+Enter) 14. SelectAdddependencyonmodule ‘mylib’thisjobaddsanotherbuild.gradle andmake all dependencytoyourmodule.
  • 9. 15. In MainActivity.javafile,inOnCreate method rightclickon “MyPerson”then select“Show ContextActions” 16. Select“ImportClass” 17. Insertcode like picture andrunproject  Firstline createsmyPersonobjectfromMyPersonclass.  Whenwe create an objectfrom a class,the constructor of the class isexecuted.  Whenwe type “myPerson.”AndroidStudio offertoussome propertyandmethodbut inthiscase we cannot see firstName orlastName andnationalIDbecause theyare private.
  • 10.  As youcan see inthe picture,the logisnotwhat I expected.Whatisthe solution?  To answerthisquestion,we needto discussthe conceptof Encapsulation. Encapsulation The meaningof Encapsulation,istomake sure that "sensitive"dataishiddenfromusers.Toachieve this,youmust: declare classvariables/attributesasprivate provide publicgetandsetmethodstoaccessand update the value of a private variable Get and Set We knowthatprivate variablescanonlybe accessedwithinthe same class(anoutside classhasno access to it).However,itispossible toaccessthemif we provide publicgetandsetmethods. The get methodreturnsthe variable value,andthe setmethodsetsthe value. Syntax forboth isthat theystart witheithergetorset,followedbythe name of the variable,withthe firstletterinuppercase. Why Encapsulation?  Bettercontrol of class attributesandmethods  Classattributescanbe made read-only(if youonlyuse the getmethod),orwrite-only(ifyou onlyuse the setmethod)  Flexible:the programmercanchange one part of the code withoutaffectingotherparts  Increasedsecurityof data 18. Go to MyPerson.classinsideclassblockpress(Alt+Enter),selectGetterandSetter
  • 11. 19. Selectall 3 variables 20. Nowchange Log in MainActivity.java As youcan see,the outputiscorrect. If your logshowsa lot of data you can searchby tag inthis case is“info”. In the followingarticles,Iwill discussotherissuesof the object-orientedprogramminginAndroid Studio. In thisarticle,Iusedthe resourcesof the www.w3schools.com. I will be happytoknowyour commentsandquestions. Sayed Mahmood Ghaemmaghami