-1

What I need to do: //Constructor that initializes b to inVal1 and the inherited a // to inVal2 by using the BaseExample constructor. public DerivedExample(int inVal1, int inVal2);

How do you call the class BaseExample's variable, in class DerivedExample by using BaseExample constructor in DerivedExample constructor? I have checked numerous articles in stackoverflow and it hasn't helped figure this out. Any help will be greatly appreciated. This is my code:

BaseExample Class (and no I am not allowed to make the variable protected on this example):

public class BaseExample {
    private int a;

    public BaseExample(int inVal) {
        a = inVal;
    }

    public BaseExample(BaseExample other){
        a = other.a;
    }

    public String toString(){
        return String.valueOf(a);
    }


}

DerivedExample Class (Updated):

public class DerivedExample extends BaseExample {
    private int b;



public DerivedExample(int inVal1, int inVal2){
        super(inVal2);
        a = inVal2;

    }
}

The super method worked. Now how would I call it if I am asked this:

Returns a reference to a string containing the value stored in the inherited varible a followed by a colon followed by the value stored in b public String toString()

I have tried this:

public String toString(){
            int base = new BaseExample(b);

            return String.valueOf(base:this.b);

        }

If I put two returns, it would give me an error of unreachable code. And if I put a super inside the valueOf it doesn't work. And this doesn't work as well. How is this executed?

userb
  • 173
  • 2
  • 15
  • 1
    Google for "constructor tutorial inheritance java", click on first link, get the answer: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html – JB Nizet May 26 '15 at 17:38

1 Answers1

1

If I understand correctly, this might be of use to you. Super can be used to call the base class's constructor to instantiate its variables for you.

Community
  • 1
  • 1
Paradox
  • 4,602
  • 12
  • 44
  • 88