Java OOP SHORT
ANSWER QUESTIONS INSTANCE
METHODS SOLUTIONS a)
Instance
variables, constructors and instance methods b)
In
terms of method headers, static methods require the word “static” after
public or private while instance methods do not have a special word as they
are the default. c)
When
calling a static method, you need the class name in front of it (unless it is
in the same class) and when calling an instance method, you need the
instance’s name in front of it (unless the instance method is in the same
class). d)
Static
methods only have access to the information passed to them via the parameter
list. Instance methods automatically
have access to the instance variables of the instance that was used to call
the method. e)
Thing
ted = new Thing(); f)
Code
(full class):
g)
ted.thatsOdd(); h)
Code (full class):
i)
4
instance variables, no instance methods, 1 constructor j)
Code: Vote election = new Vote("Donald Trump", "Joe Biden"); k)
Code: public void outputOptions() { System.out.println("Your voting options are:"); System.out.println("Option 1: " + option1); System.out.println("Option 2: " + option2); } l)
Code: //pre-condition: Choice has to be 1 or 2. public void voteFor(int choice) { if (choice == 1) count1++; else count2++; } m)
Code: public void results() { System.out.println("Voting results:"); System.out.println(option1 + ":
" + count1 + " votes"); System.out.println(option2 + ":
" + count2 + " votes"); } n)
Code: public String winner() { if (count1 > count2) return option1; else if (count2 > count1) return option2; else return "tie"; } |
||
|