Designing classes in Java

Things you need to know for an upcoming quiz.

  • What is a class?
  • What is the difference between a class and an object?
  • Difference between class variables, instance variables and local variables.
  • Definition and initialization of instance variables.
  • Creating methods (including passing parameters and returning values)
  • Creating constructors.
  • Instantiating objects using their constructor(s), setting their variables and calling their methods.

You can work through The Java Tutorial’s trail on Class and Objects. You only need to look at Classes, Objects, and More on Classes. Don’t go as far as Nested Classes. You don’t need to know about controlling access to variables using the public and private keywords at this stage, but if you are interested in going on to study Computer Science at IB Level, you might like to read that section anyway.

Exercises:

Write a Fraction class that has two instance variables numerator and denominator.

  • Add a constructor, which allows both variables to be set.

Code the following methods:

  • int getNumerator()
  • int getDenominator()
  • double getDoubleValue()
  • String toString()
  • Fraction add (Fraction f)
  • Fraction multiply (Fraction f)
  • boolean equals (Fraction f)
  • Fraction getReciprocal()

Challenge:

Find some code on the web to calculate the greatest common divisor (gdc). Use this to make sure that your fraction is always in its lowest terms, ie

Fraction f = new Fraction(2, 4);
System.out.println(f.toString());

Output:

1/2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s