3 Replies - 279 Views - Last Post: 19 December 2013 - 11:57 AM Rate Topic: -----

#1 pidgeonpancakes  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 10-August 11

Question about inheritance

Posted 19 December 2013 - 09:59 AM

I'm currently working towards taking the Oracle Java Associate Programmer exam and I'm trying to understand the nuances of inheritance/overriding & overloading methods. Can someone tell me why the code below returns "a"? I got a 46% on the last practice exam so there is alot I have to work out... ://>

 public class A
{
	protected String value;
	
	public A () {
		value = "a";
	}
	
	public String getValue() {
		return  value;
	}
	
	public void setValue() {
		value = "AAAAA";
	}

}//end class

public class B extends A
{
	protected String value;
	
	public B () {
		value = "b";
	}
	
	public String getValue(String v) {
		return  value;
	}
	
	public void setValue() {
		value = "BBBBB";
	}

}//end class

public class TestApp
{
   public static void main (String[] args)
   {
      
		A apple = new A();
		B boy = new B();
		
		System.out.println(boy.getValue());
		
   }//end main method
}//end class 


Thank you in advance for your help!

Is This A Good Question/Topic? 0
  • +

Replies To: Question about inheritance

#2 ChrisNt  Icon User is offline

  • cute bug

Reputation: 212
  • View blog
  • Posts: 647
  • Joined: 31-July 13

Re: Question about inheritance

Posted 19 December 2013 - 10:11 AM

Class B inherits method getValue() from Class A..

public String getValue() {
        return  value;
}



that method returns the field value

protected String value;


which is initialized in the constructor of class A

public A () {
    value = "a";
}


Was This Post Helpful? 1
  • +
  • -

#3 pidgeonpancakes  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 10-August 11

Re: Question about inheritance

Posted 19 December 2013 - 10:29 AM

I guess I just thought it would return a "b". When I imagined class B inheriting the getValue() method I thought it would then use it's own value variable instead of the value variable in Class A.
Was This Post Helpful? 0
  • +
  • -

#4 ChrisNt  Icon User is offline

  • cute bug

Reputation: 212
  • View blog
  • Posts: 647
  • Joined: 31-July 13

Re: Question about inheritance

Posted 19 December 2013 - 11:57 AM

What you actually did here is to overload method getValue() by adding parameter to it(which makes no sense because you dont use the parameter with name v).

public String getValue(String v) {
        return  value;
}


to override it you need to define the method as it is in class A (without any parameter..)


public String getValue() {
        return  value;
}


this will return "b" .
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1