We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I apologize for the late response (You may already know the answer to your question by now). Your code:
class MyBook extends Book{
void setTitle(String s){
s="A tale of two cities"; //This is your error
}
}
is incorrect because you might be confusing the definition of the "=" or perhaps not understanding the problem being asked.
We have an abstract class:
abstract class Book{
String title;
abstract void setTitle(String s);
}
An abstract class CANNOT create an OBJECT. In other words we cannot do this in our main() :
Book book = new Book();
The 'new Book()' creates an error (I believe) because Book is an abstract class; therefore, we cannot create an instance of it using new and calling its constructor (Book()). As a result, we have to inherit the abstract class and create an object of that class (which we will do by CREATING another class which EXTENDS Book -- aka our task for this problem):
class MyBook extends Book{
void setTitle(String s){
title = s;
}
}
As @takong mentions in his reply: you have INHERITED everything from the parent (the abstract class: Book). In other words we can access the variable 'title', or the method String getTitle() -- just like when we inherit a regular class. The only difference is in this line:
abstract class Book{
String title;
abstract void setTitle(String s); //Note the abstract
//method here!
String getTitle(){
return title;
}
}
Because of this abstract method, the class is abstract. It is OUR job as the coder to implement this method by giving it instructions on what to do when this function is called, which is why I have defined it in my MyBook class:
class MyBook extends Book{
void setTitle(String s){
title = s;
}
}
To define what each line does:
class MyBook extends Book{}
This is your standard class declaration. We have created a class called 'MyBook' which will inherit/access all the methods/abstract methods/variables from abstract class 'Book'.
void setTitle(String s){
//define here
}
Note: In our abstract class we have an abstract method that looks identical to the one here. The reason is that we are basically 'overriding' that method and IMPLEMENTING instructions of what to do when that method is called. So now whenever we CALL the function: setTitle(String s), it will do whatever is defined in that method. Also, to help you understand something about this function, the PARAMETER: 'String s' means that whenever you want to CALL THIS SPECIFIC FUNCTION, you have to PASS a STRING which this function will store in 's'. So IF we were to add an IMPLEMENTATION such as:
void setTitle(String s){
System.out.println(s);
}
Your console will print out whatever was PASSED into the function as a string. Therefore what you did in your implementation of the method:
s="A tale of two cities";
will just CHANGE the REFERENCE that s points to. As I mentioned earlier, you may be confusing the definition of '='. The equals operator basically changes the reference of the variable. In this case we have a variable that can HOLD a String type that we have named 's':
String s;
So in my main(), if I were to create a string "Hello" and pass it into the method:
void setTitle(String s){
System.out.println(s);
}
variable 's' will POINT to the string "Hello". Now an important thing to note is that String class is IMMUTABLE. That means that when you do s = "A tale of two cities" the data from s is NOT OVERWRITTEN, but a NEW string is created and now s REFERENCES or POINTS to that new string.
That is WHY we have to change our implementation to something like this:
title=s;
Remember that we INHERITED from our parent class 'Book'. 'Book' contains a variable called 'title'. So if we can make the variable title point to the same string that was passed into the function, we can call another function that is defined in the abstract class 'Book' called: 'getTitle()':
StringgetTitle(){returntitle;}
This function, when called, will return a String. What string will it return? Well if you look in the implementation it will return whatever title is pointing to. Now remember that we 'setTitle()' earlier (if you look in the main method), which we defined too! The rest is already written in the main().
Just to clarify a few things takong has mentioned in his comment/reply:
It is NOT NECESSARY to define a constructor IF YOU HAVE NOT DEFINED ANY OTHER CONSTRUCTOR because the compiler will automatically create an empty constructor (Note: It's probably good practice to write it though. Also you HAVE to define a blank constructor IF you defined a constructor WITH parameters and your program calls a PARAMETERLESS constructor -- your compiler will NOT automatically create it in this scenario I believe).
the 'super' keyword is not necessary in this case. Here's my terrible explanation of trying to explain this keyword:
In MY answer:
classMyBookextendsBook{voidsetTitle(Strings){title=s;//notice how I just directly used 'title'}}
I have directly called title because I know the compiler will only see that the parent contains the variabled called 'title'.
First off this is TERRIBLE naming schema -- it'll confuse anyone looking at your code. So what will the output be? If you guessed 9 you're correct. So if you look at main(String[] args), we defined a local variable 'num1' and set it equal to 9. We PASSED 9 into the function 'display()'. If we look at the function, 'square()' takes a parameter of type 'int' which we ALSO called 'num1' and will display num1 in console. Therefore in this example, we PASSED '9' and thus will display 9.
Now the confusion occurs when we look at the lines above it. We have a instance variable 'num1' in class Child which we set as '7'. Why was this not used? Well the function was CALLED and PASSED with int '9'; therefore, 9 will be displayed.
There is another keyword: 'this' which is a NON-STATIC reference to THAT OBJECT INSTANCE'S variable. So for example:
If we look at the main(): we have defined a local variable of type int to equal 7. Next we CREATED a new OBJECT using the NEW operator using the Child class' constructor PASSING num1 = 7. Looking above in the Child class' constructor we see that:
this.num1=num1;
we use 'this' keyword to differentiate between the local variable num1 that was PASSED INTO the function (as defined in the parameter of the function) and the instance variable num1 that was defined in the Child class. Finally, display() method is called (Please note the modification in the implementation of the function.):
publicclassChild{intnum1;//Instance variableChild(intnum1//Local variable){this.num1=num1;}voidDisplay(){System.out.println(num1);//This function prints out the INSTANCE variable num1.}publicstaticvoidmain(String[]args){intnum1=7;Childchild=newChild(num1);child.Display();//child object calls Display()}}
Finally the 'super' keyword, like the 'this' keyword, refers to the PARENT class.
In the example below:
Breaking this down line by line:
In our main() we created a LOCAL variable num1 = 9.
Then we created a Child objection called child, passing the num1 local variable = 9 into the constructor. This is the important part:
Child(intnum1){this.num1=num1;}
Notice I used the 'this' keyword. As a result the Child class' instance variable num1 references the value of 9.
The last line of our main():
child.display();
calls the display() function as described in our Child class:
voiddisplay(){System.out.println(super.num1);//NOTE the SUPER}
So this FUNCTION will display the PARENT'S (super) num1 which we have initialized at 10. Thus it will display 10.
If anything I have listed is incorrect or misleading PLEASE CORRECT ME. I am also a learning student and would love feedback.
EDIT1: Most of the java formatted code in the beginning is not showing so I just wrote it manually.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Abstract Class
You are viewing a single comment's thread. Return to all comments →
Hey Rishabh0to9,
I apologize for the late response (You may already know the answer to your question by now). Your code:
class MyBook extends Book{ void setTitle(String s){ s="A tale of two cities"; //This is your error } }
is incorrect because you might be confusing the definition of the "=" or perhaps not understanding the problem being asked.
We have an abstract class:
abstract class Book{ String title; abstract void setTitle(String s);
}
An abstract class CANNOT create an OBJECT. In other words we cannot do this in our main() :
Book book = new Book();
The 'new Book()' creates an error (I believe) because Book is an abstract class; therefore, we cannot create an instance of it using new and calling its constructor (Book()). As a result, we have to inherit the abstract class and create an object of that class (which we will do by CREATING another class which EXTENDS Book -- aka our task for this problem):
class MyBook extends Book{ void setTitle(String s){ title = s; } }
As @takong mentions in his reply: you have INHERITED everything from the parent (the abstract class: Book). In other words we can access the variable 'title', or the method String getTitle() -- just like when we inherit a regular class. The only difference is in this line:
abstract class Book{ String title; abstract void setTitle(String s); //Note the abstract
//method here! String getTitle(){ return title; } }
Because of this abstract method, the class is abstract. It is OUR job as the coder to implement this method by giving it instructions on what to do when this function is called, which is why I have defined it in my MyBook class:
class MyBook extends Book{ void setTitle(String s){ title = s; } }
To define what each line does:
class MyBook extends Book{}
This is your standard class declaration. We have created a class called 'MyBook' which will inherit/access all the methods/abstract methods/variables from abstract class 'Book'.
void setTitle(String s){ //define here } Note: In our abstract class we have an abstract method that looks identical to the one here. The reason is that we are basically 'overriding' that method and IMPLEMENTING instructions of what to do when that method is called. So now whenever we CALL the function: setTitle(String s), it will do whatever is defined in that method. Also, to help you understand something about this function, the PARAMETER: 'String s' means that whenever you want to CALL THIS SPECIFIC FUNCTION, you have to PASS a STRING which this function will store in 's'. So IF we were to add an IMPLEMENTATION such as:
void setTitle(String s){ System.out.println(s); } Your console will print out whatever was PASSED into the function as a string. Therefore what you did in your implementation of the method:
s="A tale of two cities";
will just CHANGE the REFERENCE that s points to. As I mentioned earlier, you may be confusing the definition of '='. The equals operator basically changes the reference of the variable. In this case we have a variable that can HOLD a String type that we have named 's':
String s;
So in my main(), if I were to create a string "Hello" and pass it into the method:
void setTitle(String s){ System.out.println(s); } variable 's' will POINT to the string "Hello". Now an important thing to note is that String class is IMMUTABLE. That means that when you do s = "A tale of two cities" the data from s is NOT OVERWRITTEN, but a NEW string is created and now s REFERENCES or POINTS to that new string.
That is WHY we have to change our implementation to something like this:
Remember that we INHERITED from our parent class 'Book'. 'Book' contains a variable called 'title'. So if we can make the variable title point to the same string that was passed into the function, we can call another function that is defined in the abstract class 'Book' called: 'getTitle()':
This function, when called, will return a String. What string will it return? Well if you look in the implementation it will return whatever title is pointing to. Now remember that we 'setTitle()' earlier (if you look in the main method), which we defined too! The rest is already written in the main().
Just to clarify a few things takong has mentioned in his comment/reply:
It is NOT NECESSARY to define a constructor IF YOU HAVE NOT DEFINED ANY OTHER CONSTRUCTOR because the compiler will automatically create an empty constructor (Note: It's probably good practice to write it though. Also you HAVE to define a blank constructor IF you defined a constructor WITH parameters and your program calls a PARAMETERLESS constructor -- your compiler will NOT automatically create it in this scenario I believe).
the 'super' keyword is not necessary in this case. Here's my terrible explanation of trying to explain this keyword:
In MY answer:
I have directly called title because I know the compiler will only see that the parent contains the variabled called 'title'.
This is going off topic but here is an example:
First off this is TERRIBLE naming schema -- it'll confuse anyone looking at your code. So what will the output be? If you guessed 9 you're correct. So if you look at main(String[] args), we defined a local variable 'num1' and set it equal to 9. We PASSED 9 into the function 'display()'. If we look at the function, 'square()' takes a parameter of type 'int' which we ALSO called 'num1' and will display num1 in console. Therefore in this example, we PASSED '9' and thus will display 9.
Now the confusion occurs when we look at the lines above it. We have a instance variable 'num1' in class Child which we set as '7'. Why was this not used? Well the function was CALLED and PASSED with int '9'; therefore, 9 will be displayed.
There is another keyword: 'this' which is a NON-STATIC reference to THAT OBJECT INSTANCE'S variable. So for example:
If we look at the main(): we have defined a local variable of type int to equal 7. Next we CREATED a new OBJECT using the NEW operator using the Child class' constructor PASSING num1 = 7. Looking above in the Child class' constructor we see that:
we use 'this' keyword to differentiate between the local variable num1 that was PASSED INTO the function (as defined in the parameter of the function) and the instance variable num1 that was defined in the Child class. Finally, display() method is called (Please note the modification in the implementation of the function.):
Finally the 'super' keyword, like the 'this' keyword, refers to the PARENT class. In the example below:
Breaking this down line by line: In our main() we created a LOCAL variable num1 = 9. Then we created a Child objection called child, passing the num1 local variable = 9 into the constructor. This is the important part:
Notice I used the 'this' keyword. As a result the Child class' instance variable num1 references the value of 9.
The last line of our main():
calls the display() function as described in our Child class:
So this FUNCTION will display the PARENT'S (super) num1 which we have initialized at 10. Thus it will display 10.
If anything I have listed is incorrect or misleading PLEASE CORRECT ME. I am also a learning student and would love feedback.
EDIT1: Most of the java formatted code in the beginning is not showing so I just wrote it manually.