简体   繁体   中英

Having trouble with Subclasses in java

I was reviewing one of my textbook's questions and I am slightly confused. The code is:

public class BClass
{
  private int x;

  public void set(int a)
  {
    x=a;
  }

  public void print()
  {
    System.out.print(x);
  }
}

public class DClass extends BClass
  {
    private int y;


    public void set(int a, int b)
    {
      //Postcondition: x = a; y = b;
    }

The questions are:

a. Write the definition of the print method of DClass that overrides it.

b. Write the definition of the method set of the class DClass.

For a, would I be right in saying that putting the following in the subclass would be a successful override?

public void print()
{
  System.out.print(x + " and " + y);
}

I'm also having trouble with b. Because I'm given the postcondition, it's obvious that I should set y, the instance variable in the subclass, equal to b. The problem I'm facing is how to set x equal to a. Because the instance variable x belongs to the parent class, does that make it unable to be directly accessed? Or am I allowed to do this:

public void set(int a, int b)
{
  x = a;
  y = b;
}

Would really appreciate some help, Thanks!

Below is correct. A is incorrect. I was just looking to say that is how override works. I didn't look at the validity of the method.

It should be

public void print() {
   super.print();
   System.out.print(" and " + y);
}

For B you need to invoke the super method so

public void set(int a, int b) {
   super.set(a);
   y = b;
}

x is declared private in the base class. That means that in the derived class, you cannot access it to set it or to print it. However, the base class does have public methods to do both those things. Those methods are visible to the derived class, so you can/must use those.

In DClass.print, call the print method of the base class to print x :

public void print()
{
    super.print();
    System.out.print(" and " + y);
}

The super keyword is used to call the implementation of print in the parent class. Without super. in front of the call, it would call the same print method of the derived class, which would make the same call again, rapidly crashing with a stack overflow error.

In DClass.set, you likewise need to call the set method of the base class:

public void set(int a, int b)
{
    super.set(a);
    y = b;
}

Here, super. is optional in front of the set call, because the only method named set which takes exactly 1 argument is in the base class, and it is not overridden (only overloaded ). However, including super. makes it clearer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM