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).

ie:   Math.squrt(65)                vs                  p.getX()

 

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();

Note that there is no constructor so we use the default constructor which has no parameters.

 

f)      Code (full class):

 

public class Thing

{

     public String stuff;

     public int amount;

    

     public void thatsOdd()

     {

         if (amount % 2 == 0)  //even

              System.out.println(stuff);

         else

              System.out.println("That's odd");

     }

}

 

g)    ted.thatsOdd();

h)    Code (full class):

public class Square

{

     public double sideLength;

    

     public Square(double tsl)

     {

         sideLength = tsl;

     }

    

     public double area()

     {

         return sideLength * sideLength;

     }

}

 

i)       4 instance variables, no instance methods, 1 constructor

j)       Code:

Vote election = new Vote("Donald Trump", "Joe Biden");

Another possible solution:

Vote
bestTeacher = new Vote("Mr. C.", "Mr. D.");

      

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";

     }