Find the output of Java programs | Overriding | Set 2: Enhance the knowledge of Java Overriding concepts by solving and finding the output of some Java programs.
Question 1:
class Base
{
public void fun();
}
class Derived extends Base
{
@Override
public void fun()
{
System.out.println("Derived.fun() called");
}
}
public class MethodOver
{
public static void main(String []args)
{
Base B = new Base();
B.fun();
}
}
Question 2:
class Base
{
final public void fun()
{
System.out.println("Base.fun() called");
}
}
class Derived extends Base
{
@Override
public void fun()
{
System.out.println("Derived.fun() called");
}
}
public class MethodOver
{
public static void main(String []args)
{
Base B = new Base();
B.fun();
B = new Derived();
B.fun();
}
}
Question 3:
Copy
class Base
{
void fun()
{
int i=1;
XYZ:
if(i<=5)
{
System.out.println(i*i)
i++;
goto XYZ;
}
}
}
class Derived extends Base
{
@Override
public void fun()
{
int i=1;
int n=5;
XYZ:
if(i<=10)
{
System.out.println(n*i)
i++;
goto XYZ;
}
}
}
public class MethodOver
{
public static void main(String []args)
{
Base B = new Base();
B.fun();
B = new Derived();
B.fun();
}
}
Question 4:
class Base
{
abstract void fun();
}
class Derived extends Base
{
@Override
public void fun()
{
System.out.println("Derived.fun() called");
}
}
public class MethodOver
{
public static void main(String []args)
{
Base B = new Derived();
B.fun();
}
}
Question 5
abstract class Base
{
abstract void fun();
}
class Derived extends Base
{
@Override
public void fun()
{
System.out.println("Derived.fun() called");
}
}
public class MethodOver
{
public static void main(String []args)
{
Base B = new Derived();
B.fun();
}
}
Answer Question 1:
Output:
Explanation:
The above program will generate syntax error because here we did not define the method body in the non-abstract class.
Answer Question 2:
Output:
Explanation:
The above program will generate syntax error because we here define the final fun() method in Base class and override into Derived class. But we cannot override the final method in java.
Answer Question 3:
Output:
Explanation:
The above program will generate syntax errors because we cannot use the goto statement in Java.
Answer Question 4:
Output:
Explanation:
The above program will generate syntax error because we cannot declare an abstract method in a non-abstract class in java.
Answer Question 5:
Output:
Explanation:
In the above program, we created an abstract class Base and a Derived class, the Base class contains an abstract method fun() and then we override fun() method in the Derived class.
Now look to the main() method,
Base B = new Derived(); B.fun();
Here, we created object B using Derived class constructor and then called fun() method, here fun() method of Derived class will be called and print "Derived.fun() called" on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer