(a) Write the definition of a class named \"computer\" which includes the attrib
ID: 3694686 • Letter: #
Question
(a) Write the definition of a class named "computer" which includes the attribute "name" (a string, the name of the computer) and a print method that prints out this name.
(b) Also write the definition of a class named "Macintosh" that is derived from the class "computer" (computer is the base class) and includes the attribute "color" (a string) and a method named print that prints out the computer name and color. Here is main function that will test these objects, it uses a pointer to treat a Macintosh object as a computer object, and calls the print method. Code: int main() { computer mycomputer; computer *p; Macintosh imac("Joe's IMAC","Blue"); p = &imac; p->print(); } I want the printout of this test program to be something like: Name: Joe's IMAC Color: Blue Wants the color printed out even though the computer class does not have any knowledge of the color attribute. (in other words - he wants the system to be polymorphic).
(c) How would you turn computer class into an abstract class? Show change. Also, after this change, which line in the above code will throw an error if executed
Explanation / Answer
Write the definition of a class named "computer" which includes the attribute "name" (a string, the name of the computer) and a print method that prints out this name.
public class Computer
{
String name;
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter computer name");
name=br.readLine();
public void print(String n)
{
System.out.println("computer name"+n);
}
}//class
public class Macintosh extends Computer
{
String color;
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter color");
color=br.readLine();
public void print(String n,String c)
{
Super.print(String n);
System.out.println("computer color"+c);
}
}//class
3)
public abstract class Computer
{
String name;
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter computer name");
name=br.readLine();
public void print(String n)
{
System.out.println("computer name"+n);
}
}//class
int main()
{
computer mycomputer;
computer *p;
Macintosh imac("Joe's IMAC","Blue");
p = &imac; //here error throws
p->print();
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.