Chapter 5.4.3 – Example: A Simple Card Game | Introduction to Programming Using Java
5.4.3 Example: A Simple Card Game
I will finish this section by presenting a complete program that uses the Card and Deck classes. The program lets the user play a very simple card game called HighLow. A deck of cards is shuffled, and one card is dealt from the deck and shown to the user. The user predicts whether the next card from the deck will be higher or lower than the current card. If the user predicts correctly, then the next card from the deck becomes the current card, and the user makes another prediction.
This continues until the user makes an incorrect prediction. The number of correct predictions is the user’s score.
My program has a subroutine that plays one game of HighLow. This subroutine has a return value that represents the user’s score in the game. The main() routine lets the user play several games of HighLow. At the end, it reports the user’s average score.
I won’t go through the development of the algorithms used in this program, but I encourage you to read it carefully and make sure that you understand how it works. Note in particular that the subroutine that plays one game of HighLow returns the user’s score in the game as its return value. This gets the score back to the main program, where it is needed. Here is the program:
5.5 Inheritance, Polymorphism, and Abstract Classes
A class represents a set of objects which share the same structure and behaviors. The class determines the structure of objects by specifying variables that are contained in each instance of the class, and it determines behavior by providing the instance methods that express the behavior of the objects. This is a powerful idea.
However, something like this can be done in most programming languages. The central new idea in object-oriented programming—the idea that really distinguishes it from traditional programming—is to allow classes to express the similarities among objects that share some, but not all, of their structure and behavior. Such similarities can be expressed using inheritance and polymorphism.
Read More…
Introduction to Programming Using Java – David J. Eck
Chapter 5 – Objects and Classes | Introduction to Programming Using Java
Chapter 5.1.1 – Objects, Classes and Instances | Introduction to Programming Using Java
Chapter 5.1.2 – Fundamentals of Objects | Introduction to Programming Using Java
Chapter 5.1.3 – Getters and Setters | Introduction to Programming Using Java
Chapter 5.2 – Constructors and Object Initialization | Introduction to Programming Using Java
Chapter 5.2.2 – Constructors | Introduction to Programming Using Java
1 thought on “Chapter 5.4.3 – Example: A Simple Card Game | Introduction to Programming Using Java”