0

I'm still new to programming and am trying to figure out this part of a project: The Card class represents a playing card with a rank and suit. Insert instance data that will store rank and suit as String objects and define a constructor that accepts and stores those values (rank then suit). It then says to include separate getter and setter methods for rank and suit of the card.

This may be too advanced for me but from what I can tell, I should be doing this:

public class Card
{
   private String rank;
   private String suit;
Nguyen13
  • 15
  • 4
  • 2
    Looks good. The setters are arguable, the getters (or something similar) are necessary to read the data at runtime. – Elliott Frisch Nov 14 '15 at 21:53
  • We use getters and setters to access private field instead of public fields to control access to fields from outside (encapsulation). More about this: [1](http://stackoverflow.com/a/1568230/2442133), [2](http://www.tutorialspoint.com/java/java_encapsulation.htm). – mkczyk Nov 14 '15 at 22:03

2 Answers2

1

Getters and setters are provided by Objects that allow their users to read and write their state. Internal state should be private. Private things cannot be seen outside the class... Hence the need for getters and setters.

What you have here is a POJO. Defined correctly.

Ashley Frieze
  • 4,993
  • 2
  • 29
  • 23
1

This is for maintain encapsulation and integrity inside class. A class is responsible for manage its data, and is responsible to assure the data-integrity. If you expose the data as public someone can manipulate data as he wants, so you are breaking de data encapsulation. With set/get you can control how your data is retrieved, you can provide only gets, you can do validations in set and many other things...

Basically, is an object oriented programming good practice

Francisco Hernandez
  • 2,378
  • 14
  • 18