SlideShare uma empresa Scribd logo
1 de 49
Chapter 4 Defining Your Own Classes Part 1
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Why Programmer-Defined Classes ,[object Object],[object Object],[object Object]
First Example: Using the Bicycle Class class  BicycleRegistration  { public static void  main ( String []  args ) {  Bicycle bike1, bike2; String  owner1, owner2; bike1 =  new  Bicycle ( ) ;  //Create and assign values to bike1 bike1.setOwnerName ( "Adam Smith" ) ; bike2 =  new  Bicycle ( ) ;  //Create and assign values to bike2 bike2.setOwnerName ( "Ben Jones" ) ; owner1 = bike1.getOwnerName ( ) ;  //Output the information owner2 = bike2.getOwnerName ( ) ; System.out.println ( owner1 +  " owns a bicycle." ) ;  System.out.println ( owner2 +  " also owns a bicycle." ) ;  } }
The Definition of the Bicycle Class class  Bicycle  { // Data Member   private  String ownerName; //Constructor: Initialzes the data member public  void Bicycle ( ) { ownerName =  "Unknown" ; } //Returns the name of this bicycle's owner public  String getOwnerName ( ) { return  ownerName; } //Assigns the name of this bicycle's owner public void  setOwnerName ( String name ) { ownerName = name; }  }
Multiple Instances ,[object Object],Bicycle bike1, bike2; bike1 =  new  Bicycle ( ) ; bike1.setOwnerName ( "Adam Smith" ) ; bike2 =  new  Bicycle ( ) ; bike2.setOwnerName ( "Ben Jones" ) ;
The Program Structure and Source Files There are two source files. Each class definition is stored in a separate file. To run the program: 1. javac Bicycle.java  (compile) 2. javac BicycleRegistration.java  (compile) 3. java BicycleRegistration  (run) BicycleRegistration Bicycle BicycleRegistration.java Bicycle.java
Class Diagram for Bicycle Method Listing We list the name and the data type of an argument passed to the method. Bicycle setOwnerName(String) Bicycle( ) getOwnerName( )
Template for Class Definition class { } Import Statements Class Comment Class Name Data Members Methods (incl. Constructor)
Data Member Declaration ,[object Object],Modifiers Data Type Name Note: There’s only one modifier in this example.  ,[object Object]
Method Declaration ,[object Object],[object Object],[object Object],Statements Modifier Return Type Method Name Parameter ,[object Object],[object Object],[object Object]
Constructor ,[object Object],[object Object],[object Object],[object Object],Statements Modifier Class Name Parameter public  <class name>  (  <parameters>  ){   <statements>  }
Second Example: Using Bicycle and Account class  SecondMain  { //This sample program uses both the Bicycle and Account classes public static void  main ( String []  args ) { Bicycle bike; Account acct; String  myName =  &quot;Jon Java&quot; ; bike =  new  Bicycle ( ) ;  bike.setOwnerName ( myName ) ; acct =  new  Account ( ) ; acct.setOwnerName ( myName ) ; acct.setInitialBalance ( 250.00 ) ; acct.add ( 25.00 ) ; acct.deduct ( 50 ) ; //Output some information   System.out.println ( bike.getOwnerName ()  +  &quot; owns a bicycle and&quot; ) ;  System.out.println ( &quot;has $ &quot;  + acct.getCurrentBalance ()  +  &quot; left in the bank&quot; ) ;  } }
The Account Class class  Account  { private  String ownerName; private  double balance; public  Account ( ) {   ownerName =  &quot;Unassigned&quot; ;   balance = 0.0; } public void  add ( double amt ) { balance = balance + amt; } public void  deduct ( double amt ) { balance = balance - amt; } public double  getCurrentBalance ( ) { return  balance; } public  String getOwnerName ( ) { return  ownerName; } public void  setInitialBalance ( double bal ) { balance = bal; } public void  setOwnerName ( String name )   { ownerName = name; }   } Page 1 Page 2
The Program Structure for SecondMain To run the program: 1. javac Bicycle.java  (compile) 2. javac Account.java  (compile) 2. javac SecondMain.java  (compile) 3. java SecondMain  (run) Note: You only need to compile the class once. Recompile only when you made changes in the code. SecondMain Bicycle SecondMain.java Bicycle.java Account.java Account
Arguments and Parameters ,[object Object],[object Object],class  Account  { . . . public void  add ( double amt ) { balance = balance + amt; } . . . } class  Sample  { public static void   main ( String[] arg ) { Account acct = new Account(); . . . acct.add(400); . . . } . . . } argument parameter
Matching Arguments and Parameters ,[object Object],[object Object],[object Object]
Passing Objects to a Method ,[object Object],[object Object],[object Object]
Passing a Student Object
Sharing an Object ,[object Object],[object Object]
Information Hiding and Visibility Modifiers ,[object Object],[object Object],[object Object],[object Object]
Accessibility Example Client Service ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Data Members Should Be private ,[object Object],[object Object]
Guideline for Visibility Modifiers ,[object Object],[object Object],[object Object],[object Object]
Diagram Notation for Visibility public – plus symbol (+) private – minus symbol (-)
Class Constants ,[object Object],[object Object],[object Object],[object Object],[object Object]
A Sample Use of Constants class  Dice  { private static final int  MAX_NUMBER =  6; private static final int  MIN_NUMBER = 1; private static final int  NO_NUMBER = 0; private int  number; public  Dice ( ) { number = NO_NUMBER; } //Rolls the dice public void  roll ( ) { number =  ( int )   ( Math.floor ( Math.random ()  *  ( MAX_NUMBER - MIN_NUMBER + 1 ))  + MIN_NUMBER ) ; } //Returns the number on this dice public int  getNumber ( ) { return  number; }   }
Local Variables ,[object Object],public  double convert ( int num ) { double result; result = Math.sqrt(num * num); return  result;  } local variable
Local, Parameter & Data Member ,[object Object],[object Object],[object Object],[object Object],[object Object]
Sample Matching class  MusicCD  { private  String  artist; private  String  title; private  String  id; public  MusicCD ( String name1, String name2 ) { String ident; artist = name1; title  = name2; ident  = artist.substring ( 0,2 )  +  &quot;-&quot;  +    title.substring ( 0,9 ) ; id  = ident; } ... }
Calling Methods of the Same Class ,[object Object],[object Object],[object Object]
Changing Any Class to a Main Class ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Problem Statement ,[object Object],[object Object]
Overall Plan ,[object Object],[object Object],[object Object],[object Object]
Required Classes input computation output LoanCalculator Loan JOptionPane PrintStream
Development Steps ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Step 1 Design ,[object Object],Gets three input values private getInput Displays the output private displayOutput Displays a short description of a program private describeProgram Give three parameters, compute the monthly and total payments private computePayment Starts the loan calcution. Calls other methods public start Purpose Visibility Method
Step 1 Code ,[object Object],[object Object],[object Object],[object Object],Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.
Step 1 Test ,[object Object],inside describeProgram inside getInput inside computePayment inside displayOutput
Step 2 Design ,[object Object],[object Object],[object Object]
Step 2 Code ,[object Object],[object Object],[object Object],[object Object]
Step 2 Test ,[object Object],[object Object],System.out.println ( &quot;Loan Amount: $&quot;   + loan.getAmount ()) ; System.out.println ( &quot;Annual Interest Rate:&quot;   + loan.getRate ()  +  &quot;%&quot; ); System.out.println ( &quot;Loan Period (years):&quot;   + loan.getPeriod ()) ;
Step 3 Design ,[object Object],[object Object]
Step 3 Code ,[object Object],[object Object],[object Object],[object Object]
Step 3 Test ,[object Object],[object Object]
Step 4 Design ,[object Object],[object Object],[object Object]
Step 4 Code ,[object Object],[object Object],[object Object],[object Object]
Step 4 Test ,[object Object]
Step 5: Finalize ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

Mais conteúdo relacionado

Mais procurados

02 - Orientação a objetos e revisão de C# v1.5
02 - Orientação a objetos e revisão de C# v1.502 - Orientação a objetos e revisão de C# v1.5
02 - Orientação a objetos e revisão de C# v1.5César Augusto Pessôa
 
Presentasi konsep dasar html
Presentasi konsep dasar htmlPresentasi konsep dasar html
Presentasi konsep dasar htmlDedy Setiawan
 
CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations Rob LaPlaca
 
Specificity and CSS Selectors
Specificity and CSS SelectorsSpecificity and CSS Selectors
Specificity and CSS Selectorspalomateach
 
object oriented Programming ppt
object oriented Programming pptobject oriented Programming ppt
object oriented Programming pptNitesh Dubey
 
Php Simple Xml
Php Simple XmlPhp Simple Xml
Php Simple Xmlmussawir20
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented languagefarhan amjad
 
Lessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML DevicesLessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML DevicesICS
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining ClassesIntro C# Book
 
Friends function and_classes
Friends function and_classesFriends function and_classes
Friends function and_classesasadsardar
 
Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Asfand Hassan
 
computer project code ''payroll'' (based on datafile handling)
computer project code ''payroll'' (based on datafile handling)computer project code ''payroll'' (based on datafile handling)
computer project code ''payroll'' (based on datafile handling)Nitish Yadav
 

Mais procurados (15)

02 - Orientação a objetos e revisão de C# v1.5
02 - Orientação a objetos e revisão de C# v1.502 - Orientação a objetos e revisão de C# v1.5
02 - Orientação a objetos e revisão de C# v1.5
 
Presentasi konsep dasar html
Presentasi konsep dasar htmlPresentasi konsep dasar html
Presentasi konsep dasar html
 
CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations
 
Specificity and CSS Selectors
Specificity and CSS SelectorsSpecificity and CSS Selectors
Specificity and CSS Selectors
 
Python cgi programming
Python cgi programmingPython cgi programming
Python cgi programming
 
POO - 16 - Polimorfismo
POO - 16 - PolimorfismoPOO - 16 - Polimorfismo
POO - 16 - Polimorfismo
 
object oriented Programming ppt
object oriented Programming pptobject oriented Programming ppt
object oriented Programming ppt
 
Gstreamer plugin development
Gstreamer plugin development Gstreamer plugin development
Gstreamer plugin development
 
Php Simple Xml
Php Simple XmlPhp Simple Xml
Php Simple Xml
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented language
 
Lessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML DevicesLessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML Devices
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
Friends function and_classes
Friends function and_classesFriends function and_classes
Friends function and_classes
 
Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)
 
computer project code ''payroll'' (based on datafile handling)
computer project code ''payroll'' (based on datafile handling)computer project code ''payroll'' (based on datafile handling)
computer project code ''payroll'' (based on datafile handling)
 

Semelhante a Chapter 4 - Defining Your Own Classes - Part I

Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_typesAbed Bukhari
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsFALLEE31188
 
03 Object Relational Mapping
03 Object Relational Mapping03 Object Relational Mapping
03 Object Relational MappingRanjan Kumar
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6sotlsoc
 
Chapter22 static-class-member-example
Chapter22 static-class-member-exampleChapter22 static-class-member-example
Chapter22 static-class-member-exampleDeepak Singh
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined MethodPRN USM
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsMayank Jain
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with JavaJussi Pohjolainen
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4dplunkett
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methodsfarhan amjad
 

Semelhante a Chapter 4 - Defining Your Own Classes - Part I (20)

Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
03 Object Relational Mapping
03 Object Relational Mapping03 Object Relational Mapping
03 Object Relational Mapping
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
Chapter22 static-class-member-example
Chapter22 static-class-member-exampleChapter22 static-class-member-example
Chapter22 static-class-member-example
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
02.adt
02.adt02.adt
02.adt
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
Lecture5
Lecture5Lecture5
Lecture5
 
C++lecture9
C++lecture9C++lecture9
C++lecture9
 
OOP and C++Classes
OOP and C++ClassesOOP and C++Classes
OOP and C++Classes
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
ccc
cccccc
ccc
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
 
C++ classes
C++ classesC++ classes
C++ classes
 

Mais de Eduardo Bergavera

CLP Session 5 - The Christian Family
CLP Session 5 - The Christian FamilyCLP Session 5 - The Christian Family
CLP Session 5 - The Christian FamilyEduardo Bergavera
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismEduardo Bergavera
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingEduardo Bergavera
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and StringsEduardo Bergavera
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summaryEduardo Bergavera
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaEduardo Bergavera
 
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software DevelopmentChapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software DevelopmentEduardo Bergavera
 

Mais de Eduardo Bergavera (9)

CLP Session 5 - The Christian Family
CLP Session 5 - The Christian FamilyCLP Session 5 - The Christian Family
CLP Session 5 - The Christian Family
 
What is Python?
What is Python?What is Python?
What is Python?
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and Polymorphism
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software DevelopmentChapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software Development
 

Último

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 

Último (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 

Chapter 4 - Defining Your Own Classes - Part I

  • 1. Chapter 4 Defining Your Own Classes Part 1
  • 2.
  • 3.
  • 4. First Example: Using the Bicycle Class class BicycleRegistration { public static void main ( String [] args ) { Bicycle bike1, bike2; String owner1, owner2; bike1 = new Bicycle ( ) ; //Create and assign values to bike1 bike1.setOwnerName ( &quot;Adam Smith&quot; ) ; bike2 = new Bicycle ( ) ; //Create and assign values to bike2 bike2.setOwnerName ( &quot;Ben Jones&quot; ) ; owner1 = bike1.getOwnerName ( ) ; //Output the information owner2 = bike2.getOwnerName ( ) ; System.out.println ( owner1 + &quot; owns a bicycle.&quot; ) ; System.out.println ( owner2 + &quot; also owns a bicycle.&quot; ) ; } }
  • 5. The Definition of the Bicycle Class class Bicycle { // Data Member private String ownerName; //Constructor: Initialzes the data member public void Bicycle ( ) { ownerName = &quot;Unknown&quot; ; } //Returns the name of this bicycle's owner public String getOwnerName ( ) { return ownerName; } //Assigns the name of this bicycle's owner public void setOwnerName ( String name ) { ownerName = name; } }
  • 6.
  • 7. The Program Structure and Source Files There are two source files. Each class definition is stored in a separate file. To run the program: 1. javac Bicycle.java (compile) 2. javac BicycleRegistration.java (compile) 3. java BicycleRegistration (run) BicycleRegistration Bicycle BicycleRegistration.java Bicycle.java
  • 8. Class Diagram for Bicycle Method Listing We list the name and the data type of an argument passed to the method. Bicycle setOwnerName(String) Bicycle( ) getOwnerName( )
  • 9. Template for Class Definition class { } Import Statements Class Comment Class Name Data Members Methods (incl. Constructor)
  • 10.
  • 11.
  • 12.
  • 13. Second Example: Using Bicycle and Account class SecondMain { //This sample program uses both the Bicycle and Account classes public static void main ( String [] args ) { Bicycle bike; Account acct; String myName = &quot;Jon Java&quot; ; bike = new Bicycle ( ) ; bike.setOwnerName ( myName ) ; acct = new Account ( ) ; acct.setOwnerName ( myName ) ; acct.setInitialBalance ( 250.00 ) ; acct.add ( 25.00 ) ; acct.deduct ( 50 ) ; //Output some information System.out.println ( bike.getOwnerName () + &quot; owns a bicycle and&quot; ) ; System.out.println ( &quot;has $ &quot; + acct.getCurrentBalance () + &quot; left in the bank&quot; ) ; } }
  • 14. The Account Class class Account { private String ownerName; private double balance; public Account ( ) { ownerName = &quot;Unassigned&quot; ; balance = 0.0; } public void add ( double amt ) { balance = balance + amt; } public void deduct ( double amt ) { balance = balance - amt; } public double getCurrentBalance ( ) { return balance; } public String getOwnerName ( ) { return ownerName; } public void setInitialBalance ( double bal ) { balance = bal; } public void setOwnerName ( String name ) { ownerName = name; } } Page 1 Page 2
  • 15. The Program Structure for SecondMain To run the program: 1. javac Bicycle.java (compile) 2. javac Account.java (compile) 2. javac SecondMain.java (compile) 3. java SecondMain (run) Note: You only need to compile the class once. Recompile only when you made changes in the code. SecondMain Bicycle SecondMain.java Bicycle.java Account.java Account
  • 16.
  • 17.
  • 18.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25. Diagram Notation for Visibility public – plus symbol (+) private – minus symbol (-)
  • 26.
  • 27. A Sample Use of Constants class Dice { private static final int MAX_NUMBER = 6; private static final int MIN_NUMBER = 1; private static final int NO_NUMBER = 0; private int number; public Dice ( ) { number = NO_NUMBER; } //Rolls the dice public void roll ( ) { number = ( int ) ( Math.floor ( Math.random () * ( MAX_NUMBER - MIN_NUMBER + 1 )) + MIN_NUMBER ) ; } //Returns the number on this dice public int getNumber ( ) { return number; } }
  • 28.
  • 29.
  • 30. Sample Matching class MusicCD { private String artist; private String title; private String id; public MusicCD ( String name1, String name2 ) { String ident; artist = name1; title = name2; ident = artist.substring ( 0,2 ) + &quot;-&quot; + title.substring ( 0,9 ) ; id = ident; } ... }
  • 31.
  • 32.
  • 33.
  • 34.
  • 35. Required Classes input computation output LoanCalculator Loan JOptionPane PrintStream
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.