• Register
+2 votes
10 views

Problem:

I am assuming a bunch of helpful souls are roaming here, in Kodlogs. I am trying to figuring out the abstract method in Java and wrote a simple program on it. Unfortunately, my program throws back an error and says,

AbstractClassExample.java:9: error: AbstractClassExample is not abstract and does
not override abstract method setAge(int) in MyClass
public class AbstractClassExample extends MyClass{
       ^
1 error

It may be tough to give the solution before knowing the original program. Please, find my program snippet below:

import java.io.IOException;
abstract class MyClass {
   public abstract void display();
   public abstract void setName(String name);
   public abstract void setAge(int age);
}
public class AbstractClassExample extends MyClass{
   public void display(){
      System.out.println("This is the subclass");
   }
   public static void main(String args[]) {
      new AbstractClassExample().display();
   }
}

Do you have any idea or solution for me? Thanks, guys.

ago by (6k points)  

1 Answer

+1 vote

Solution:

First of all, you have to have a clear concept of an abstract method and abstract class. A method is more like a machine that helps us to execute a particular job within a wink in our program. A method that doesn’t have a body is called an abstract method.  It has an abstract keyword before it like this:  public abstract myMethod();

On the other hand, A class which contains 0 or more abstract methods is known as abstract class. If it contains at least one abstract method, it must be declared abstract.

So, understanding above all these, to make this program work you either need to override all the abstract methods of the super-class or, make the subclass abstract as shown below :

abstract class MyClass {
   public abstract void display();
   public abstract void setName(String name);
   public abstract void setAge(int age);
}
public abstract class AbstractClassExample extends MyClass{
   public void display(){
      System.out.println("This is the subclass");
   }
}

Never stop asking. Please, reply to this thread if you still have any confusion.

Thanks.

ago by (17.8k points)  
...