Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Object-oriented language basics, Part 4

Inheritance: Build objects in layers

  • Print
  • Feedback

Page 6 of 10

class Super
{
   double x = 2;
   void draw ()
   {
      System.out.println ("Super");
   }
}
class Sub extends Super
{
   double x = 3;
   void draw ()
   {
      System.out.println ("Sub");
      System.out.println ("x = " + x);
      System.out.println ("super.x = " + super.x); // Access the superclass x field.
      super.draw (); // Call the superclass draw() method.
   }
}


The code fragment above reveals another use for the super keyword. Prefixing super. to either a field name or a method call results in the superclass field being accessed or the superclass method being called. If you were to execute new Sub ().draw (); against the above code fragment, the following would print:

Sub
x = 3.0
super.x = 2.0
Super


Suppose that, in the Circle and Sub classes in the code fragments above, you declare the draw() method private -- as in private void draw(). If you do that and then execute the code, the compiler will report an error because you cannot make a field or method's accessibility more restrictive in a subclass.

A subclass method can only override a superclass method if the superclass method is both accessible and nonfinal. You declare a final method by using the final keyword. For example, suppose Super declares draw() as follows: final void draw () { System.out.println ("Super"); }. Attempting to compile the above code fragment with the newly marked final draw() method results in a compiler error.

  • Print
  • Feedback

Resources