The given Java code is an example of Object-Oriented Programming (OOP) that uses abstract and concrete classes to model a book. The abstract class 'Book' has a 'title' attribute and an abstract method 'setTitle'. The concrete class 'MyBook' extends 'Book' and implements the 'setTitle' method. The main function creates an instance of 'MyBook', sets its title, and prints it.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The solution approach is based on the concept of abstraction in OOP. An abstract class 'Book' is defined with a 'title' attribute and an abstract 'setTitle' method. A concrete class 'MyBook' is then created that extends 'Book' and provides an implementation for the 'setTitle' method. In the main function, an instance of 'MyBook' is created, its title is set using user input, and then the title is printed. The use of an abstract class allows for flexibility in setting the title of a book, as different subclasses could potentially set the title in different ways.
/**
*
*/
package com.javaaid.hackerrank.solutions.languages.java.oop;
import java.util.Scanner;
/**
*
*/
abstract class Book {
String title;
abstract void setTitle(String s);
String getTitle() {
return title;
}
}
// Write MyBook class here
class MyBook extends Book {
void setTitle(String s) {
super.title = s;
}
}
public class JavaAbstractClass {
public static void main(String[] args) {
// Book new_novel=new Book(); This line prHMain.java:25: error: Book is
// abstract; cannot be instantiated
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();
}
}
If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.