Java Abstract class program with Java HackerRank Solutions
Problem:
Following is an example of abstract class:
abstract class Book{
String title;
abstract void setTitle(String s);
String getTitle(){
return title;
}
}
If you try to create an instance of this class like the following line you will get an error:
Book new_novel=new Book();
You have to create another class that extends the abstract class. Then you can create an instance of the new class.
Notice that setTitle method is abstract too and has no body. That means you must implement the body of that method in the child class.
In the editor, we have provided the abstract Book class and a Main class. In the Main class, we created an instance of a class called MyBook. Your task is to write just the MyBook class.
Your class mustn't be public.
Sample Input
A tale of two cities
Sample Output
The title is: A tale of
Solution:
import java.util.*;
abstract class Book{
String title;
abstract void setTitle(String s);
String getTitle(){
return title;
}
}
class MyBook extends Book {
void setTitle(String s) {
this.title = s;
}
}
public class Main{
public static void main(String []args){
Scanner sc=new Scanner(System.in);
String title=sc.nextLine();
MyBook new_novel=new MyBook();
new_novel.setTitle(title);
System.out.println("The title is: "+new_novel.getTitle());
sc.close();
}
}
Steps involved in this solution:
1. The code starts with the definition of an abstract class named Book
. It has a title
attribute and an abstract method setTitle(String s)
2. The MyBook class is introduced to extend the abstract class Book
. It provides an implementation for the abstract method setTitle..
3. The Main class serves as the entry point of the program. A Scanner is initialized to read input from the standard input.
4. The program prompts the user to input a title using sc.nextLine().
5. An instance of the MyBook class named new_novel is created.
6. The setTitle method of MyBook is called to set the title with the user-inputted value.
7. The program prints the title using System.out.println("The title is: " + new_novel.getTitle())
.
8. The Scanner is closed to prevent resource leaks using sc.close().
9. Run the program, and it will wait for user input. Input a title when prompted, and the program will display the entered title.
10. The program showcases the use of abstract classes, method implementation in a concrete class, and object instantiation.
11. Test the program with different input values to see how it sets and retrieves the book title.