Question

I was given a problem to solve:

A Book, which as a title, author, and year of publication. Include methods to get and set the private instance variables and a toString method to display the object. Also create a method moreRecent which takes two books as input parameters and returns the one that was published more recently. Create 3 JUnit tests for moreRecent.

I think the part about creating a method "moreRecent" is easy enough, but I don't get what the problem means by getting and setting the private instance variables and a tostring method to display the object. Does anybody know what it means and show me, because I am really confused. Thanks a lot!

Thanks, I believe I solved it.

Was it helpful?

Solution

An instance variable is a variable that can be unique for each instance of the class.

A variable that is not an instance variable will be shared by all instances of the class.

If a variable is declared static it will be shared by all instances of the class, if the variable is not declared as static it will be unique for each instance of the class, thus an instance variable.

Declaring a non-static variable as private will not allow other classes to access it directly, thus a private instance variable.

Thus in order to access it you must create (usually public) getter and setter methods within that class to allow other classes to access those private instance variables in a way you define in the getter/setter methods instead of allowing full control over the variable you can choose to put up limits etc within the methods.

As for the toString method, it's a method of the Object class (which is the base class of all other classes) and you can override it to suit your needs. (You can look that up in google)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top