In: Computer Science
Shirt inherits Clothing. Clothing has the fold()method, but Shirt does not. Which fold() is executed in the following code?
Shirt myShirt = new Shirt();
myShirt.fold()
Group of answer choices
This results in a runtime error.
The Shirt version
This results in a compiler error.
The Clothing version
Shirt inherits Clothing. What would be the effect of the following code?
Clothing myShirt = new Shirt();
Group of answer choices
The code compiles and runs.
A compiler error
A runtime error
Shirt inherits Clothing. What would be the effect of the following code?
Shirt myShirt = new Clothing();
Group of answer choices
A runtime error
The code compiles and runs.
A compiler error
Answers:
Question 1: The Clothing version
-> As the Shirt inherits Clothing so the object of the Shirt class can call the method of Clothing.
Program:
class Clothing
{
void fold()
{
System.out.println("Clothing class Method!!");
}
}
class Shirt extends Clothing
{
}
class Test
{
public static void main(String args[])
{
Shirt myShirt=new Shirt();
myShirt.fold();
}
}
Output:
Question 2: The code compiles and runs.
Program:
class Clothing
{
void fold()
{
System.out.println("Clothing class Method!!");
}
}
class Shirt extends Clothing
{
}
class Test
{
public static void main(String args[])
{
Clothing myShirt=new Shirt();
myShirt.fold();
}
}
Output:
Question 3: A compile error
-> Compile error: incompatible types: Clothing cannot be converted to Shirt.
Program:
class Clothing
{
void fold()
{
System.out.println("Clothing class Method!!");
}
}
class Shirt extends Clothing
{
}
class Test
{
public static void main(String args[])
{
Shirt myShirt = new Clothing();
myShirt.fold();
}
}
Output: