Class that is extended from an abstract class toString method doesn't work :/

1437 views java
-3

This is the main demo class

public class Ongoing{

  public static void main(String[] args){

    ExtendsAbstract josh = new ExtendsAbstract(5, "donkey");

    System.out.println(josh.toString());



  }

}

this is the class extended from the abstract class, the one who's tostring method won't work.

public class ExtendsAbstract extends Abstract{

  private String t;

  public ExtendsAbstract(int y, String t){
    super(y);
    this.t = t;
  }

  public String getString(){
    return this.t;  
  }

  public int getInt(){
    return super.getInt();
  }

  public String toString(int y){

    return(/*super.toString(y)+*/"The integer is "+ y) ;

  }

}

This is the abstract class

public abstract class Abstract{

  private int y;


  public Abstract(int y){
    this.y = y;
  }

  public int getInt(){
    return y;
  }

  public String toString(int y){
    return("The integer is :"+y);
  }


}

Every time i try and access the toString method from the extended class it just prints out what i think is a memory address. I even didn't mess with the abstract class and it still did that, does anyone know why? Also another question about abstract classes, what advantages do they bring, is it just memory? Because you can't access private members from it so isn't it the same as a normal class, just more restrictions?

answered question

You're calling the java.lang.Object implementation of toString (all java classes inherit from this). Your implementation of toString is expecting an integer.

None of your classes override Object#toString(). You have toString(int) but are calling toString()

1 Answer

7

You didn't override toString() method from Object since that method has no parameters. You just created one more overloaded method.

posted this

Have an answer?

JD

Please login first before posting an answer.