SlideShare a Scribd company logo
Class Design Examples
Problem Solving Solving a problem means that we know the way or the method to follow manually from the start till the end. Having the method known, the same method is used by the computer to solve the problem but faster with higher precision. If we do not know how to solve a problem ourselves, the computer will not be of any help in this regard. The strategy for solving a problem goes through the following stages: Analysis: in this stage, we should find  what  the problem should do. Design : the way or method of  how  your problem is solved is produced Implementation: the method found in design is then coded here in a given programming language. Testing: here we verify that the program written is working correctly Deployment : finally the program is ready to use
Problem Solving Strategy
The Class Design Steps Before starting any coding, good programmers should always design the classes. A class design consists of deciding following What data they will contain  How they will behave After class design and coding, its objects are used. We’ll learn all the above steps by designing a class  Car  and a class  CheckingAccount .
Example 1: Designing a Car Class A class  “Car”  that calculates miles per gallon.   What data it will contain ?  Variables int startMiles;      // Starting odometer reading  int endMiles;       // Ending odometer reading  double gallons;    // Gallons of gas used between the readings  How it will behave ? Constructors   Car ( int startOdo, int endingOdo, double gallons )  Creates a new instance of a Car object with the starting and ending odometer readings and the number of gallons of gas consumed.  Methods double calculateMPG()   calculates and returns the miles per gallon for the car.
Class Definition: Step by Step   import java.io.* ; class Car  {  // instance variables  // constructor  // methods  }   class MilesPerGallon  {  .............. }
Class Definition: Step by Step import java.io.* ; class Car  {  // instance variables int startMiles; // Stating odometer reading  int endMiles; // Ending odometer reading  double gallons; // Gallons of gas used between the readings  // constructor  // methods  }  class MilesPerGallon  {  .................... }
Class Definition: Step by Step import java.io.* ; class Car  {  // instance variables int startMiles; // Stating odometer reading  int endMiles; // Ending odometer reading  double gallons; // Gallons of gas used between the readings  // constructor  Car( int first, int last, double gals )  {  startMiles = first; endMiles = last; gallons = gals;  }  // methods  }   class MilesPerGallon  {  .................... }
Complete Program import java.io.* ; class Car  {  // instance variables int startMiles; // Stating odometer reading  int endMiles; // Ending odometer reading  double gallons; // Gallons of gas used between the readings  // constructor  Car( int first, int last, double gals )  {  startMiles = first; endMiles = last; gallons = gals;  }  // methods double calculateMPG( )  {  return (endMiles - startMiles)/gallons ;  }   }
Complete Program (cont .....) class MilesPerGallon  {  public static void main( String[] args )  {  Car car = new Car( 32456, 32810, 10.6 );  System.out.println( "Miles per gallon is " + car.calculateMPG() );  } }
Two Car Objects Can several objects of type Car be constructed ?   Yes import java.io.* ; class Car  { ....................... } class MilesPerGallon  {  public static void main( String[] args )  {  Car car1 = new Car( 32456, 32810, 10.6 );  System.out.println( "Miles per gallon of car1 is " + car1.calculateMPG() );  Car car2 = new Car( 100000, 100300, 10.6 );  System.out.println( "Miles per gallon of car 2 is " + car2.calculateMPG() );   } }
Example 2: Designing a class “CheckingAccount” To design “CheckingAccount” class, we follow the same steps which we followed for class Car.  Requirement analysis: What data it will contain Account number.  Name of account holder.  Current balance.  Design: How it will behave (what actions will be performed on a checking account) Accept a deposit.  Process a check.  Get the current balance. Also, we need a  constructor  to create objects from the class.
Example 2: Designing a class “CheckingAccount” class CheckingAccount  {  // instance variables String accountNumber;  String accountHolder;  int balance;  // constructor   // methods }
Class Definition class CheckingAccount {  // instance variables   String accountNumber;  String accountHolder;  int balance;  //constructor   CheckingAccount( String accNumber, String holder, int start )  {  accountNumber = accNumber ;  accountHolder = holder ;  balance = start ;  }  // methods   }
CheckingAccount: More Requirements Analysis The requirements also describe what each method does.  For example,  The method  Accept a deposit  adds an amount to the current balance. The method  Process a check  subtracts a given amount  from the current balance. The method  Get the current balance  returns the current balance in checking account Following the above requirements, now we can write method definitions.
Complete Class class CheckingAccount {  // instance variables   .......  //constructor   ................ // methods   int currentBalance() {  return balance ;  }  void processDeposit( int amount ) {  balance = balance + amount ;  }  void processCheck( int amount ) {  balance = balance – amount } }
Using a CheckingAccount Object class CheckingAccount {  . . . . ......... }  class CheckingAccountTester {  public static void main( String[] args ) {  CheckingAccount account1 = new CheckingAccount( "123",  "Bob", 100 );  System.out.println( account1.currentBalance() );  account1.processDeposit( 2000 );  account1.processCheck( 1500 );  System.out.println( account1.currentBalance() ); } }
Encapsulation and Visibility Modifiers
What is “Encapsulation” So far, the objects we have designed, have all of their members (variables and methods) visible to any part of the program. Thus, code outside of an object can access (see and change) the object's members. A better OOP design enforces  encapsulation: Some (or all) of an object's member variables and methods should be visible  only  to the object's own methods. Thus, code outside of the object should not be allowed to access these members directly.
Why is “Encapsulation” Encapsulation provides security to object data by specifying who is allowed to access one of its variables or methods. The encapsulation can be achieved by using visibility modifiers.
The “private” visibility modifier When a member (a variable or method) of a class is declared  private  it can be used only by the methods of that class.  class CheckingAccount  {  // instance variables   private  String accountNumber;    private  String accountHolder;    private  int balance;  .................. }   Now only the methods of a CheckingAccount object can access the values in accountNumber, accountHolder, and balance.
main can’t access private members class CheckingAccountTester { public static void main( String[] args ) {  CheckingAccount bobsAccount = new CheckingAccount( "999",  "Bob", 100 );  System.out.println(bobsAccount.balance); bobsAccount.balance = bobsAccount.balance + 200; System.out.println( bobsAccount.balance );  } } What happens when we try to compile the above program ? We get a  Compilation Errors  because  balance  is  private,  and therefore main( ) is not allowed to access its value. How can main( ) access the balance of a CheckingAccount object ?     By using  Access Method
Access Methods A class with private members, controls access to those members by using  access methods .  An access method is a method which is used to access the private members of the class is visible to other classes (usually public). The outside code can access private members of an object only by using access methods. For example, main() can access balance of a CheckingAccount object by using the access methods  currentBalance()
CheckingAccount Class with Access Methods class CheckingAccount {  // instance variables  .......  //constructor  ................ // Access methods   int currentBalance() {  return balance ;  }  void processDeposit( int amount ) {  balance = balance + amount ;  }  void processCheck( int amount ) {  balance = balance – amount; } }
main uses access methods to access private members class CheckingAccountTester {  public static void main( String[] args ) {  CheckingAccount account1 = new  CheckingAccount( "123", "Bob", 100 );  System.out.println( account1.currentBalance());  account1.processDeposit( 2000 );  account1.processCheck( 1500 );  System.out.println(account1.currentBalance()); } }  class CheckingAccountTester { public static void main( String[] args ) {  CheckingAccount bobsAccount =  new CheckingAccount("999","Bob", 100);   System.out.println(bobsAccount.balance); bobsAccount.balance =  bobsAccount.balance + 2000; bobsAccount.balance =  bobsAccount.balance -1500; System.out.println( bobsAccount.balance );  } }
Private Methods Can we have a private method in a class?  Yes private method  can be used only by the other methods of the object. Program code outside the object cannot directly use a private method of the object.  Say that the bank wants to keep track of how many times each checking account is used.  A "use" of the checking account is processing a deposit  processDeposit()  or processing a check  processCheck() .
Private Methods Example: incrementUse( ) To do this, we add the following members to CheckingAccount class:   A private variable "useCount“ A private method “incrementUse” The incrementUse() is used by processDeposit() and processCheck() methods each time they are used, to increase the value of useCount by (1).
CheckingAccount class with incrementUse( ) class CheckingAccount {  private String accountNumber;  private String accountHolder;  private int balance;  private   int useCount = 0; private void incrementUse( ) {  useCount = useCount + 1;  } void processDeposit( int amount ) {  balance = balance + amount ; incrementUse( );  }  void processCheck( int amount ) {  balance = balance – amount; incrementUse( );  } }
main can’t use private method The main() cannot use the private variable useCount nor can it use the private method incrementUse().  The main()  can  use bobsAccount.processCheck() which is not private. It in turn uses the private method incrementUse(). class CheckingAccountTester {  public static void main( String[ ] args ) {  CheckingAccount bobsAccount = new  CheckingAccount( "999", "Bob", 100 ); bobsAccount.processCheck( 50 );  } }
display( ) Method As main() cannot access the private variables, so it is good idea to have a display() method to print the private variables.  class CheckingAccount {  private String accountNumber; private String accountHolder; private int balance;  private int useCount = 0; . . . . . . . . . .  void display( ) {  System.out.println( accountNumber + "\t" + accountHolder +  "\t" + balance "\t" + useCount );   }  }
The public Visibility Modifier The  public  access modifier explicitly says that a method or variable of an object can be accessed by code outside of the object.  The access methods are intended for outsiders, and have to be visible to outsiders in order to be useful.  So, the  public  visibility modifier is usually used for all access methods and constructors in a class definition.
The public Visibility Modifier class CheckingAccount {  private String accountNumber;  private String accountHolder;  private int balance;  private   int useCount = 0; private void incrementUse( ) { .........} public CheckingAccount( String accNumber, String holder, int start ) { . . . . } public void processDeposit( int amount ) { . . . . } public void processCheck( int amount ) { . . . . } public int currentBalance( ) { . . . . } public void display( ) { . . . . }  }
Default Visibility If you do not specify public or private for a variable or a method, then it will have default visibility.  Default visibility allows a variable or method to be seen within all methods of a class or other classes that are part of the same  package .  For now, default visibility means about the same thing as public visibility. But it is best to explicitly declare members public if that is what you actually need.  You can not explicitly declare a member of a class to have default visibility (for example, you can't say default int monthlyCharge; )
Parameters, Local Variables, Overloading
Parameters and Local Variables An object stores its  state  as values in its instance variables. But sometimes an object's methods work with values that are  not  part of an object's state. These values are stored in the  parameters  and  local variables .
A  parameter  is a  variable name  used in a method definition. class CheckingAccount { . . . .  private int balance; . . . .  void processDeposit(int  amount ) { balance = balance +  amount  ;  } }   What is a Parameter
What is the use of a Parameter It is used to store the values passed to the method by its callers. In this example, the value  200  passed by main() is stored in the parameter “ amount” class CheckingAccountTester { public static void main(String[] args) {  CheckingAccount bobsAccount=  new CheckingAccount("999", "Bob", 100 );  bobsAccount.processDeposit(  200  ); } }
Formal and Actual Parameters Formal parameter —the identifier used in a method definition in which the value is passed. amount  is a formal parameter of  processDeposit Actual parameter —the actual value that is passed into the method by a caller.  200  is an actual parameter of  processDeposit .
Scope of a Parameter The scope of a parameter is the body of its method.   class CheckingAccount { void processDeposit(int  amount ) {  // scope of  amount  starts here   balance = balance +  amount  ;  // scope of  amount  ends here   }  void display() { System.out.println(balance+"\t"+  amount ;  //syntax error  }  }   The  display()  method is outside the scope of  amount .
Local Variables A  local variable  is a variable that is declared inside of the body of a method.  It is used to hold a temporary value. class CheckingAccount {  private int balance;  void processCheck(int amount) { int charge;  // scope of  charge  starts here  ........................   //  scope of  charge  ends here   } }
Method Overloading Overloading  is when two or more methods of a class have  the same name but have different parameter lists .  When one of the methods is called, it is made clear which one is wanted  by matching the actual parameter list to the formal parameter lists .
Method Overloading class CheckingAccount { private int balance;   . . . .  void processDeposit( int amount )  { balance = balance + amount ;   }  void processDeposit( int amount, int serviceCharge )  {  balance = balance + amount - serviceCharge;   } }  class CheckingAccountTester { public static void main( String[] args ) {  CheckingAccount bobsAccount =  new CheckingAccount( "999", "Bob", 100 );  bobsAccount.processDeposit( 200 );  // call to first bobsAccount.processDeposit( 200, 25 );  // call to second  } }
Method Signature The  signature  of a method is:  Its name.  The number and types of its parameters, in order.  For example, the signatures of the two  processDeposit  methods are:  processDeposit( int )  processDeposit( int, int )  The signatures of the methods in a class must be unique.  The return type is not part of the signature
Call by Value & Primitive Parameters Java uses  call by value  for parameters. Changes to the primitive parameter do not affect the Caller class SimpleClass {  public void work( int x ) {  x = 100;  // local change to the formal parameter  } }  class SimpleTester {  public static void main ( String[] args ) {  int var = 7;  SimpleClass simple = new SimpleClass();  System.out.println("First value of the local var: " + var );  simple.work( var );   System.out.println("Second value of the local var: " + var );  } }  Output First value of the local var: 7 Second value of the local var: 7
Object Parameters An object can also be passed as a parameter to a method. Again call by value is used, but now the value is a  reference  to an object. Using a object reference parameter, the  contents  of a mutable object can be changed, and the change will affect the caller.  However,  Immutable objects (like String objects) can‘t be changed
class MyPoint {  public int x=3, y=5 ;  public void print() {  System.out.println("x = " + x + "; y = " + y );  } }  class PointDoubler { public void twice( MyPoint parm ) { parm.x = parm.x * 2 ; parm.y = parm.y * 2 ; } }  class PointTester {  public static void main ( String[ ] args ) {  MyPoint pt = new MyPoint( );  PointDoubler dbl = new PointDoubler( ); pt.print( ); dbl.twice( pt ); pt.print(); } }   Mutable Object Parameters: MyPoint x = 3; y = 5 x = 6; y = 10
class ObjectPrinter {  public void print( String st ) {  st = "Hah! A second Object!" ;  }}  class OPTester2 {  public static void main ( String[] args ) {  String message = “Welcome" ;  ObjectPrinter op = new ObjectPrinter( );  System.out.println("First value of message: " + message );   op.print( message );  System.out.println("Second value of message: " + message ); } }  Immutable Object Parameters: String First value of message: Welcome Second value of message: Welcome

More Related Content

What's hot (20)

PDF
Data base management system LAB MANUAL KCS 551.pdf
VandanaTripathi32
 
PPTX
Introduction to numpy Session 1
Jatin Miglani
 
PPTX
Binary arithmetic
Elizabeth de Leon Aler
 
PPTX
Queue Data Structure
Afaq Mansoor Khan
 
PPSX
Collections - Array List
Hitesh-Java
 
DOCX
Data Structure Project File
Deyvessh kumar
 
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
PPTX
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
Suraj Kumar
 
PPTX
Stacks IN DATA STRUCTURES
Sowmya Jyothi
 
PDF
Datastructure
Griffinder VinHai
 
PDF
Network programming Using Python
Karim Sonbol
 
PPTX
Functions in python
colorsof
 
PPT
Unit I Advanced Java Programming Course
parveen837153
 
PDF
sparse matrix in data structure
MAHALAKSHMI P
 
PDF
Algorithms Lecture 3: Analysis of Algorithms II
Mohamed Loey
 
PPTX
File handling in Python
Megha V
 
PPTX
Introduction to OOP in Python
Aleksander Fabijan
 
PPSX
Data Structure (Queue)
Adam Mukharil Bachtiar
 
PPT
Bucket sort
Hossain Md Shakhawat
 
Data base management system LAB MANUAL KCS 551.pdf
VandanaTripathi32
 
Introduction to numpy Session 1
Jatin Miglani
 
Binary arithmetic
Elizabeth de Leon Aler
 
Queue Data Structure
Afaq Mansoor Khan
 
Collections - Array List
Hitesh-Java
 
Data Structure Project File
Deyvessh kumar
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
Suraj Kumar
 
Stacks IN DATA STRUCTURES
Sowmya Jyothi
 
Datastructure
Griffinder VinHai
 
Network programming Using Python
Karim Sonbol
 
Functions in python
colorsof
 
Unit I Advanced Java Programming Course
parveen837153
 
sparse matrix in data structure
MAHALAKSHMI P
 
Algorithms Lecture 3: Analysis of Algorithms II
Mohamed Loey
 
File handling in Python
Megha V
 
Introduction to OOP in Python
Aleksander Fabijan
 
Data Structure (Queue)
Adam Mukharil Bachtiar
 

Viewers also liked (20)

PPTX
Classes, objects in JAVA
Abhilash Nair
 
PPSX
Learn java objects inheritance-overriding-polymorphism
TOPS Technologies
 
PPT
Unt 3 attributes, methods, relationships-1
gopal10scs185
 
PDF
Insight & Solving Design Problem with Design Sprint Method
Ngurah Devara Udayana
 
PPSX
Problem solving and design
Renée Howard-Johnson
 
PPT
Unit 4 designing classes
gopal10scs185
 
PPTX
OGDC2013_Game design problem solving_Mr Nguyen Chi Hieu
ogdc
 
PPT
Unit 4
gopal10scs185
 
PPT
Program design and problem solving techniques
Dokka Srinivasu
 
PPT
Unit 3 object analysis-classification
gopal10scs185
 
PPT
Object and Classes in Java
backdoor
 
PPT
HISTORY OF ARCHITECTURE EDUCATION: POTENTIALS AND LIMITATIONS FOR A BETTER DE...
Iman Gawad
 
PPT
Operating System Chapter 4 Multithreaded programming
guesta40f80
 
PDF
Design Theory - Lecture 02: Design processes & Problem solving
Bas Leurs
 
PPTX
Learning Design for Problem-Solving
Global OER Graduate Network
 
PPTX
Class object method constructors in java
Raja Sekhar
 
PPTX
Constructor ppt
Vinod Kumar
 
PPT
OS Process and Thread Concepts
sgpraju
 
Classes, objects in JAVA
Abhilash Nair
 
Learn java objects inheritance-overriding-polymorphism
TOPS Technologies
 
Unt 3 attributes, methods, relationships-1
gopal10scs185
 
Insight & Solving Design Problem with Design Sprint Method
Ngurah Devara Udayana
 
Problem solving and design
Renée Howard-Johnson
 
Unit 4 designing classes
gopal10scs185
 
OGDC2013_Game design problem solving_Mr Nguyen Chi Hieu
ogdc
 
Program design and problem solving techniques
Dokka Srinivasu
 
Unit 3 object analysis-classification
gopal10scs185
 
Object and Classes in Java
backdoor
 
HISTORY OF ARCHITECTURE EDUCATION: POTENTIALS AND LIMITATIONS FOR A BETTER DE...
Iman Gawad
 
Operating System Chapter 4 Multithreaded programming
guesta40f80
 
Design Theory - Lecture 02: Design processes & Problem solving
Bas Leurs
 
Learning Design for Problem-Solving
Global OER Graduate Network
 
Class object method constructors in java
Raja Sekhar
 
Constructor ppt
Vinod Kumar
 
OS Process and Thread Concepts
sgpraju
 
Ad

Similar to Java: Class Design Examples (20)

PPT
Java căn bản - Chapter4
Vince Vo
 
PPT
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
PPT
Ap Power Point Chpt4
dplunkett
 
PPT
Ch03
Gus Sandoval
 
PPT
Ch03
ojac wdaj
 
PPTX
Chap2 class,objects
raksharao
 
PPTX
Java Chapter 04 - Writing Classes: part 4
DanWooster1
 
PPT
ObjectOrientedSystems.ppt
ChishaleFriday
 
PPTX
3_ObjectOrientedSystems.pptx
RokaKaram
 
PPT
C0 review core java1
tam53pm1
 
PPTX
Object oriented concepts
Gousalya Ramachandran
 
PPT
Class & Object - Intro
PRN USM
 
PPTX
Object Oriented Programming Concepts
SanmatiRM
 
PPT
CHAPTER 1 - OVERVIEW OOP.ppt
NgoHuuNhan1
 
PPTX
Java 2
Michael Shrove
 
PPT
Explain Classes and methods in java (ch04).ppt
ayaankim007
 
PPTX
Class as the Basis of all Computation.pptx
kinjalahuja087
 
PPT
Chapter 7 - Defining Your Own Classes - Part II
Eduardo Bergavera
 
PPT
Methods.ppt
ssuser42a548
 
PPTX
14. Java defining classes
Intro C# Book
 
Java căn bản - Chapter4
Vince Vo
 
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
Ap Power Point Chpt4
dplunkett
 
Ch03
ojac wdaj
 
Chap2 class,objects
raksharao
 
Java Chapter 04 - Writing Classes: part 4
DanWooster1
 
ObjectOrientedSystems.ppt
ChishaleFriday
 
3_ObjectOrientedSystems.pptx
RokaKaram
 
C0 review core java1
tam53pm1
 
Object oriented concepts
Gousalya Ramachandran
 
Class & Object - Intro
PRN USM
 
Object Oriented Programming Concepts
SanmatiRM
 
CHAPTER 1 - OVERVIEW OOP.ppt
NgoHuuNhan1
 
Explain Classes and methods in java (ch04).ppt
ayaankim007
 
Class as the Basis of all Computation.pptx
kinjalahuja087
 
Chapter 7 - Defining Your Own Classes - Part II
Eduardo Bergavera
 
Methods.ppt
ssuser42a548
 
14. Java defining classes
Intro C# Book
 
Ad

More from Tareq Hasan (20)

PPTX
Grow Your Career with WordPress
Tareq Hasan
 
PDF
Caching in WordPress
Tareq Hasan
 
PDF
How to Submit a plugin to WordPress.org Repository
Tareq Hasan
 
PDF
Composer - The missing package manager for PHP
Tareq Hasan
 
PDF
WordPress Theme & Plugin development best practices - phpXperts seminar 2011
Tareq Hasan
 
PPT
08 c++ Operator Overloading.ppt
Tareq Hasan
 
PPT
02 c++ Array Pointer
Tareq Hasan
 
PPT
01 c++ Intro.ppt
Tareq Hasan
 
PPT
chapter22.ppt
Tareq Hasan
 
PPT
chapter - 6.ppt
Tareq Hasan
 
PPT
Algorithm.ppt
Tareq Hasan
 
PPT
chapter-8.ppt
Tareq Hasan
 
PPT
chapter23.ppt
Tareq Hasan
 
PPT
chapter24.ppt
Tareq Hasan
 
PPT
Algorithm: priority queue
Tareq Hasan
 
PPT
Algorithm: Quick-Sort
Tareq Hasan
 
PPT
Java: GUI
Tareq Hasan
 
PPT
Java: Inheritance
Tareq Hasan
 
PPT
Java: Exception
Tareq Hasan
 
PPT
Java: Introduction to Arrays
Tareq Hasan
 
Grow Your Career with WordPress
Tareq Hasan
 
Caching in WordPress
Tareq Hasan
 
How to Submit a plugin to WordPress.org Repository
Tareq Hasan
 
Composer - The missing package manager for PHP
Tareq Hasan
 
WordPress Theme & Plugin development best practices - phpXperts seminar 2011
Tareq Hasan
 
08 c++ Operator Overloading.ppt
Tareq Hasan
 
02 c++ Array Pointer
Tareq Hasan
 
01 c++ Intro.ppt
Tareq Hasan
 
chapter22.ppt
Tareq Hasan
 
chapter - 6.ppt
Tareq Hasan
 
Algorithm.ppt
Tareq Hasan
 
chapter-8.ppt
Tareq Hasan
 
chapter23.ppt
Tareq Hasan
 
chapter24.ppt
Tareq Hasan
 
Algorithm: priority queue
Tareq Hasan
 
Algorithm: Quick-Sort
Tareq Hasan
 
Java: GUI
Tareq Hasan
 
Java: Inheritance
Tareq Hasan
 
Java: Exception
Tareq Hasan
 
Java: Introduction to Arrays
Tareq Hasan
 

Recently uploaded (20)

PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 

Java: Class Design Examples

  • 2. Problem Solving Solving a problem means that we know the way or the method to follow manually from the start till the end. Having the method known, the same method is used by the computer to solve the problem but faster with higher precision. If we do not know how to solve a problem ourselves, the computer will not be of any help in this regard. The strategy for solving a problem goes through the following stages: Analysis: in this stage, we should find what the problem should do. Design : the way or method of how your problem is solved is produced Implementation: the method found in design is then coded here in a given programming language. Testing: here we verify that the program written is working correctly Deployment : finally the program is ready to use
  • 4. The Class Design Steps Before starting any coding, good programmers should always design the classes. A class design consists of deciding following What data they will contain How they will behave After class design and coding, its objects are used. We’ll learn all the above steps by designing a class Car and a class CheckingAccount .
  • 5. Example 1: Designing a Car Class A class “Car” that calculates miles per gallon. What data it will contain ? Variables int startMiles;      // Starting odometer reading int endMiles;       // Ending odometer reading double gallons;    // Gallons of gas used between the readings How it will behave ? Constructors Car ( int startOdo, int endingOdo, double gallons ) Creates a new instance of a Car object with the starting and ending odometer readings and the number of gallons of gas consumed. Methods double calculateMPG() calculates and returns the miles per gallon for the car.
  • 6. Class Definition: Step by Step import java.io.* ; class Car { // instance variables // constructor // methods } class MilesPerGallon { .............. }
  • 7. Class Definition: Step by Step import java.io.* ; class Car { // instance variables int startMiles; // Stating odometer reading int endMiles; // Ending odometer reading double gallons; // Gallons of gas used between the readings // constructor // methods } class MilesPerGallon { .................... }
  • 8. Class Definition: Step by Step import java.io.* ; class Car { // instance variables int startMiles; // Stating odometer reading int endMiles; // Ending odometer reading double gallons; // Gallons of gas used between the readings // constructor Car( int first, int last, double gals ) { startMiles = first; endMiles = last; gallons = gals; } // methods } class MilesPerGallon { .................... }
  • 9. Complete Program import java.io.* ; class Car { // instance variables int startMiles; // Stating odometer reading int endMiles; // Ending odometer reading double gallons; // Gallons of gas used between the readings // constructor Car( int first, int last, double gals ) { startMiles = first; endMiles = last; gallons = gals; } // methods double calculateMPG( ) { return (endMiles - startMiles)/gallons ; } }
  • 10. Complete Program (cont .....) class MilesPerGallon { public static void main( String[] args ) { Car car = new Car( 32456, 32810, 10.6 ); System.out.println( "Miles per gallon is " + car.calculateMPG() ); } }
  • 11. Two Car Objects Can several objects of type Car be constructed ? Yes import java.io.* ; class Car { ....................... } class MilesPerGallon { public static void main( String[] args ) { Car car1 = new Car( 32456, 32810, 10.6 ); System.out.println( "Miles per gallon of car1 is " + car1.calculateMPG() ); Car car2 = new Car( 100000, 100300, 10.6 ); System.out.println( "Miles per gallon of car 2 is " + car2.calculateMPG() ); } }
  • 12. Example 2: Designing a class “CheckingAccount” To design “CheckingAccount” class, we follow the same steps which we followed for class Car. Requirement analysis: What data it will contain Account number. Name of account holder. Current balance. Design: How it will behave (what actions will be performed on a checking account) Accept a deposit. Process a check. Get the current balance. Also, we need a constructor to create objects from the class.
  • 13. Example 2: Designing a class “CheckingAccount” class CheckingAccount { // instance variables String accountNumber; String accountHolder; int balance; // constructor // methods }
  • 14. Class Definition class CheckingAccount { // instance variables String accountNumber; String accountHolder; int balance; //constructor CheckingAccount( String accNumber, String holder, int start ) { accountNumber = accNumber ; accountHolder = holder ; balance = start ; } // methods }
  • 15. CheckingAccount: More Requirements Analysis The requirements also describe what each method does. For example, The method Accept a deposit adds an amount to the current balance. The method Process a check subtracts a given amount from the current balance. The method Get the current balance returns the current balance in checking account Following the above requirements, now we can write method definitions.
  • 16. Complete Class class CheckingAccount { // instance variables ....... //constructor ................ // methods int currentBalance() { return balance ; } void processDeposit( int amount ) { balance = balance + amount ; } void processCheck( int amount ) { balance = balance – amount } }
  • 17. Using a CheckingAccount Object class CheckingAccount { . . . . ......... } class CheckingAccountTester { public static void main( String[] args ) { CheckingAccount account1 = new CheckingAccount( "123", "Bob", 100 ); System.out.println( account1.currentBalance() ); account1.processDeposit( 2000 ); account1.processCheck( 1500 ); System.out.println( account1.currentBalance() ); } }
  • 19. What is “Encapsulation” So far, the objects we have designed, have all of their members (variables and methods) visible to any part of the program. Thus, code outside of an object can access (see and change) the object's members. A better OOP design enforces encapsulation: Some (or all) of an object's member variables and methods should be visible only to the object's own methods. Thus, code outside of the object should not be allowed to access these members directly.
  • 20. Why is “Encapsulation” Encapsulation provides security to object data by specifying who is allowed to access one of its variables or methods. The encapsulation can be achieved by using visibility modifiers.
  • 21. The “private” visibility modifier When a member (a variable or method) of a class is declared private it can be used only by the methods of that class. class CheckingAccount { // instance variables private String accountNumber; private String accountHolder; private int balance; .................. } Now only the methods of a CheckingAccount object can access the values in accountNumber, accountHolder, and balance.
  • 22. main can’t access private members class CheckingAccountTester { public static void main( String[] args ) { CheckingAccount bobsAccount = new CheckingAccount( "999", "Bob", 100 ); System.out.println(bobsAccount.balance); bobsAccount.balance = bobsAccount.balance + 200; System.out.println( bobsAccount.balance ); } } What happens when we try to compile the above program ? We get a Compilation Errors because balance is private, and therefore main( ) is not allowed to access its value. How can main( ) access the balance of a CheckingAccount object ?  By using Access Method
  • 23. Access Methods A class with private members, controls access to those members by using access methods . An access method is a method which is used to access the private members of the class is visible to other classes (usually public). The outside code can access private members of an object only by using access methods. For example, main() can access balance of a CheckingAccount object by using the access methods currentBalance()
  • 24. CheckingAccount Class with Access Methods class CheckingAccount { // instance variables ....... //constructor ................ // Access methods int currentBalance() { return balance ; } void processDeposit( int amount ) { balance = balance + amount ; } void processCheck( int amount ) { balance = balance – amount; } }
  • 25. main uses access methods to access private members class CheckingAccountTester { public static void main( String[] args ) { CheckingAccount account1 = new CheckingAccount( "123", "Bob", 100 ); System.out.println( account1.currentBalance()); account1.processDeposit( 2000 ); account1.processCheck( 1500 ); System.out.println(account1.currentBalance()); } } class CheckingAccountTester { public static void main( String[] args ) { CheckingAccount bobsAccount = new CheckingAccount("999","Bob", 100); System.out.println(bobsAccount.balance); bobsAccount.balance = bobsAccount.balance + 2000; bobsAccount.balance = bobsAccount.balance -1500; System.out.println( bobsAccount.balance ); } }
  • 26. Private Methods Can we have a private method in a class? Yes private method can be used only by the other methods of the object. Program code outside the object cannot directly use a private method of the object. Say that the bank wants to keep track of how many times each checking account is used. A "use" of the checking account is processing a deposit processDeposit() or processing a check processCheck() .
  • 27. Private Methods Example: incrementUse( ) To do this, we add the following members to CheckingAccount class: A private variable "useCount“ A private method “incrementUse” The incrementUse() is used by processDeposit() and processCheck() methods each time they are used, to increase the value of useCount by (1).
  • 28. CheckingAccount class with incrementUse( ) class CheckingAccount { private String accountNumber; private String accountHolder; private int balance; private int useCount = 0; private void incrementUse( ) { useCount = useCount + 1; } void processDeposit( int amount ) { balance = balance + amount ; incrementUse( ); } void processCheck( int amount ) { balance = balance – amount; incrementUse( ); } }
  • 29. main can’t use private method The main() cannot use the private variable useCount nor can it use the private method incrementUse(). The main() can use bobsAccount.processCheck() which is not private. It in turn uses the private method incrementUse(). class CheckingAccountTester { public static void main( String[ ] args ) { CheckingAccount bobsAccount = new CheckingAccount( "999", "Bob", 100 ); bobsAccount.processCheck( 50 ); } }
  • 30. display( ) Method As main() cannot access the private variables, so it is good idea to have a display() method to print the private variables. class CheckingAccount { private String accountNumber; private String accountHolder; private int balance; private int useCount = 0; . . . . . . . . . . void display( ) { System.out.println( accountNumber + "\t" + accountHolder + "\t" + balance "\t" + useCount ); } }
  • 31. The public Visibility Modifier The public access modifier explicitly says that a method or variable of an object can be accessed by code outside of the object. The access methods are intended for outsiders, and have to be visible to outsiders in order to be useful. So, the public visibility modifier is usually used for all access methods and constructors in a class definition.
  • 32. The public Visibility Modifier class CheckingAccount { private String accountNumber; private String accountHolder; private int balance; private int useCount = 0; private void incrementUse( ) { .........} public CheckingAccount( String accNumber, String holder, int start ) { . . . . } public void processDeposit( int amount ) { . . . . } public void processCheck( int amount ) { . . . . } public int currentBalance( ) { . . . . } public void display( ) { . . . . } }
  • 33. Default Visibility If you do not specify public or private for a variable or a method, then it will have default visibility. Default visibility allows a variable or method to be seen within all methods of a class or other classes that are part of the same package . For now, default visibility means about the same thing as public visibility. But it is best to explicitly declare members public if that is what you actually need. You can not explicitly declare a member of a class to have default visibility (for example, you can't say default int monthlyCharge; )
  • 35. Parameters and Local Variables An object stores its state as values in its instance variables. But sometimes an object's methods work with values that are not part of an object's state. These values are stored in the parameters and local variables .
  • 36. A parameter is a variable name used in a method definition. class CheckingAccount { . . . . private int balance; . . . . void processDeposit(int amount ) { balance = balance + amount ; } } What is a Parameter
  • 37. What is the use of a Parameter It is used to store the values passed to the method by its callers. In this example, the value 200 passed by main() is stored in the parameter “ amount” class CheckingAccountTester { public static void main(String[] args) { CheckingAccount bobsAccount= new CheckingAccount("999", "Bob", 100 ); bobsAccount.processDeposit( 200 ); } }
  • 38. Formal and Actual Parameters Formal parameter —the identifier used in a method definition in which the value is passed. amount is a formal parameter of processDeposit Actual parameter —the actual value that is passed into the method by a caller. 200 is an actual parameter of processDeposit .
  • 39. Scope of a Parameter The scope of a parameter is the body of its method. class CheckingAccount { void processDeposit(int amount ) { // scope of amount starts here balance = balance + amount ; // scope of amount ends here } void display() { System.out.println(balance+"\t"+ amount ; //syntax error } } The display() method is outside the scope of amount .
  • 40. Local Variables A local variable is a variable that is declared inside of the body of a method. It is used to hold a temporary value. class CheckingAccount { private int balance; void processCheck(int amount) { int charge; // scope of charge starts here ........................ // scope of charge ends here } }
  • 41. Method Overloading Overloading is when two or more methods of a class have the same name but have different parameter lists . When one of the methods is called, it is made clear which one is wanted by matching the actual parameter list to the formal parameter lists .
  • 42. Method Overloading class CheckingAccount { private int balance; . . . . void processDeposit( int amount ) { balance = balance + amount ; } void processDeposit( int amount, int serviceCharge ) { balance = balance + amount - serviceCharge; } } class CheckingAccountTester { public static void main( String[] args ) { CheckingAccount bobsAccount = new CheckingAccount( "999", "Bob", 100 ); bobsAccount.processDeposit( 200 ); // call to first bobsAccount.processDeposit( 200, 25 ); // call to second } }
  • 43. Method Signature The signature of a method is: Its name. The number and types of its parameters, in order. For example, the signatures of the two processDeposit methods are: processDeposit( int ) processDeposit( int, int ) The signatures of the methods in a class must be unique. The return type is not part of the signature
  • 44. Call by Value & Primitive Parameters Java uses call by value for parameters. Changes to the primitive parameter do not affect the Caller class SimpleClass { public void work( int x ) { x = 100; // local change to the formal parameter } } class SimpleTester { public static void main ( String[] args ) { int var = 7; SimpleClass simple = new SimpleClass(); System.out.println("First value of the local var: " + var ); simple.work( var ); System.out.println("Second value of the local var: " + var ); } } Output First value of the local var: 7 Second value of the local var: 7
  • 45. Object Parameters An object can also be passed as a parameter to a method. Again call by value is used, but now the value is a reference to an object. Using a object reference parameter, the contents of a mutable object can be changed, and the change will affect the caller. However, Immutable objects (like String objects) can‘t be changed
  • 46. class MyPoint { public int x=3, y=5 ; public void print() { System.out.println("x = " + x + "; y = " + y ); } } class PointDoubler { public void twice( MyPoint parm ) { parm.x = parm.x * 2 ; parm.y = parm.y * 2 ; } } class PointTester { public static void main ( String[ ] args ) { MyPoint pt = new MyPoint( ); PointDoubler dbl = new PointDoubler( ); pt.print( ); dbl.twice( pt ); pt.print(); } } Mutable Object Parameters: MyPoint x = 3; y = 5 x = 6; y = 10
  • 47. class ObjectPrinter { public void print( String st ) { st = "Hah! A second Object!" ; }} class OPTester2 { public static void main ( String[] args ) { String message = “Welcome" ; ObjectPrinter op = new ObjectPrinter( ); System.out.println("First value of message: " + message ); op.print( message ); System.out.println("Second value of message: " + message ); } } Immutable Object Parameters: String First value of message: Welcome Second value of message: Welcome