SlideShare a Scribd company logo
1 of 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]

More Related Content

What's hot

Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
Vince Vo
 
03 Object Relational Mapping
03 Object Relational Mapping03 Object Relational Mapping
03 Object Relational Mapping
Ranjan Kumar
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
backdoor
 

What's hot (20)

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
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
 
Object & classes
Object & classes Object & classes
Object & classes
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 
08slide
08slide08slide
08slide
 
CLASSES, STRUCTURE,UNION in C++
CLASSES, STRUCTURE,UNION in C++CLASSES, STRUCTURE,UNION in C++
CLASSES, STRUCTURE,UNION in C++
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual Basic
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
Lecture09
Lecture09Lecture09
Lecture09
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
03 Object Relational Mapping
03 Object Relational Mapping03 Object Relational Mapping
03 Object Relational Mapping
 
Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 

Viewers also liked

Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
Vince Vo
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
Vince Vo
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2
Vince Vo
 

Viewers also liked (7)

Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 
Rama Ch14
Rama Ch14Rama Ch14
Rama Ch14
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2
 
Rama Ch12
Rama Ch12Rama Ch12
Rama Ch12
 
Rama Ch7
Rama Ch7Rama Ch7
Rama Ch7
 
Rama Ch11
Rama Ch11Rama Ch11
Rama Ch11
 

Similar to Java căn bản - Chapter4

Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
Abed Bukhari
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
FALLEE31188
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
sotlsoc
 
Chapter22 static-class-member-example
Chapter22 static-class-member-exampleChapter22 static-class-member-example
Chapter22 static-class-member-example
Deepak Singh
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
PRN USM
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
Jussi Pohjolainen
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
dplunkett
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
farhan amjad
 

Similar to Java căn bản - Chapter4 (20)

Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
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
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining 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
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 

More from Vince Vo

Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13
Vince Vo
 
Java căn bản - Chapter10
Java căn bản - Chapter10Java căn bản - Chapter10
Java căn bản - Chapter10
Vince Vo
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
Vince Vo
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
Vince Vo
 
Java căn bản - Chapter5
Java căn bản - Chapter5Java căn bản - Chapter5
Java căn bản - Chapter5
Vince Vo
 
Java căn bản - Chapter3
Java căn bản - Chapter3Java căn bản - Chapter3
Java căn bản - Chapter3
Vince Vo
 
Java căn bản- Chapter1
Java  căn bản- Chapter1Java  căn bản- Chapter1
Java căn bản- Chapter1
Vince Vo
 
Hướng dẫn cài đặt Java
Hướng dẫn cài đặt JavaHướng dẫn cài đặt Java
Hướng dẫn cài đặt Java
Vince Vo
 

More from Vince Vo (19)

Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13
 
Java căn bản - Chapter10
Java căn bản - Chapter10Java căn bản - Chapter10
Java căn bản - Chapter10
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 
Java căn bản - Chapter5
Java căn bản - Chapter5Java căn bản - Chapter5
Java căn bản - Chapter5
 
Java căn bản - Chapter3
Java căn bản - Chapter3Java căn bản - Chapter3
Java căn bản - Chapter3
 
Java căn bản- Chapter1
Java  căn bản- Chapter1Java  căn bản- Chapter1
Java căn bản- Chapter1
 
Hướng dẫn cài đặt Java
Hướng dẫn cài đặt JavaHướng dẫn cài đặt Java
Hướng dẫn cài đặt Java
 
Rama Ch13
Rama Ch13Rama Ch13
Rama Ch13
 
Rama Ch12
Rama Ch12Rama Ch12
Rama Ch12
 
Rama Ch10
Rama Ch10Rama Ch10
Rama Ch10
 
Rama Ch8
Rama Ch8Rama Ch8
Rama Ch8
 
Rama Ch9
Rama Ch9Rama Ch9
Rama Ch9
 
Rama Ch6
Rama Ch6Rama Ch6
Rama Ch6
 
Rama Ch5
Rama Ch5Rama Ch5
Rama Ch5
 
Rama Ch4
Rama Ch4Rama Ch4
Rama Ch4
 
Rama Ch3
Rama Ch3Rama Ch3
Rama Ch3
 
Rama Ch2
Rama Ch2Rama Ch2
Rama Ch2
 
Rama Ch1
Rama Ch1Rama Ch1
Rama Ch1
 

Recently uploaded

SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
CaitlinCummins3
 
Poster_density_driven_with_fracture_MLMC.pdf
Poster_density_driven_with_fracture_MLMC.pdfPoster_density_driven_with_fracture_MLMC.pdf
Poster_density_driven_with_fracture_MLMC.pdf
Alexander Litvinenko
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
中 央社
 
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
Krashi Coaching
 

Recently uploaded (20)

How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
 Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING IIII BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
 
Implanted Devices - VP Shunts: EMGuidewire's Radiology Reading Room
Implanted Devices - VP Shunts: EMGuidewire's Radiology Reading RoomImplanted Devices - VP Shunts: EMGuidewire's Radiology Reading Room
Implanted Devices - VP Shunts: EMGuidewire's Radiology Reading Room
 
Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17
 
How to Analyse Profit of a Sales Order in Odoo 17
How to Analyse Profit of a Sales Order in Odoo 17How to Analyse Profit of a Sales Order in Odoo 17
How to Analyse Profit of a Sales Order in Odoo 17
 
Poster_density_driven_with_fracture_MLMC.pdf
Poster_density_driven_with_fracture_MLMC.pdfPoster_density_driven_with_fracture_MLMC.pdf
Poster_density_driven_with_fracture_MLMC.pdf
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
 
Word Stress rules esl .pptx
Word Stress rules esl               .pptxWord Stress rules esl               .pptx
Word Stress rules esl .pptx
 
philosophy and it's principles based on the life
philosophy and it's principles based on the lifephilosophy and it's principles based on the life
philosophy and it's principles based on the life
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptx
 

Java căn bản - Chapter4

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