+ 1

java abstract classes

The program you are given receives name and age of student as input. Complete the program to set the values for the corresponding attributes of the Student class and prints out the final result. If the age is <0, program should output "Invalid age" and assign a 0 value to the age attribute. Sample Input Olivia -2 Sample Output Invalid age Name: Olivia Age: 0 Explanation -2 is invalid value for age attribute, that's why "Invalid age" and "Age: 0" is printed. Setter and Getter should handle this. You need to handle the conditions inside the Getter and the Setter. class Main { public static void main(String[] args) { //do not touch this code Monopoly monopoly = new Monopoly(); Chess chess = new Chess(); Battleships battleships = new Battleships(); monopoly.play(); chess.play(); battleships.play(); } } abstract class Game { abstract String getName(); abstract void play(); public String name; } class Monopoly extends Game { //give "Monopoly" name to game String getName() { return name = "Monopoly"; } // play method should print "Buy all property." void play() { System.out.println("Buy all property."); } } class Chess extends Game { //give "Chess" name to game String getName() { return name = "Chess"; } // play method should print "Kill the enemy king" void play() { System.out.println("Kill the enemy king"); } } class Battleships extends Game { //give "Battleships" name to game String getName() { return name = "Battleships"; } // play method should print "Sink all ships" void play() { System.out.println("Sink all ships"); } }

5th May 2022, 10:35 AM
ite hephzi
ite hephzi - avatar
3 Respostas
+ 2
What is your actual question? Is there any relation between the code you posted with the task? I can't see any?
5th May 2022, 11:12 AM
Jayakrishna 🇮🇳
0
if you start rewriting this example, it will look like: public class Person_test { public static void main(String[] args) { //touch this code // input name age .. Student xy = new Student(..); System.out.println( xy); } } class Person { public String name; // age // Person(..name, ..age) { // if (valid input) {} // } String getName(); // .. getAge() {} //public String toString() {} } class Student extends Person {} //(but it's not done)
5th May 2022, 4:18 PM
zemiak
0
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); String name = read.nextLine(); int age = read.nextInt(); Student student = new Student(); student.name = name; //set the age via Setter student.setAge(age); System.out.println("Name: " + student.name); System.out.println("Age: " + student.getAge()); } } class Student { public String name; private int age; public int getAge() { //complete Getter return age; } public void setAge(int age) { //complete Setter if(age<0){ System.out.println("Invalid age"); this.age=0; } } }
9th Mar 2023, 2:02 PM
Akash Ramesh Joshi