Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call abstract class methods to another class in java

can anybody tell me that. how can I call abstract class method to my own class in java?

thanks in advance

like image 775
shiv1229 Avatar asked Jan 03 '12 10:01

shiv1229


2 Answers

First of all look at you abstract class, it shall contain abstract methods and real methods. In the following sample the Foo class has an abstract method (FooMethod) and a real method (Yeee).

public abstract class Foo {

  public abstract int FooMethod(int i);

  public int Yeeee() {
    for (int i = 0; i < 3; i++) {
       int res = FooMethod(i);
       // Do whatever
    }
  }
}

Abstract class are not meant to be directly used, so we have to inherit from them with a concrete class. The following inherits from the abstract (implementing the abstract method)

public class Bar extends Foo {
  public int FooMethod(int i) {
    // do something with i
  }

  public static void main (string [] args) {
      Bar obj = new Bar();
      obj.Yeeee();
  }
}

Note: when in the main you call obj.Yeee() the base class method gets invoked, but in place of the abstract FooMethod, your own new implementation is used.

This is just the tip of the iceberg with abstract classes, but roughly should point you to the right direction.

Please take a good read here is a good tutorial and should give you some initial wisdom about inheritance and abstract classes.

like image 195
BigMike Avatar answered Oct 19 '22 03:10

BigMike


You need to first create a subclass of the abstract class. This will then contain the methods of that abstract class. You use the "extends" keyword.

For example:

public class MyClass extends AbstractClass 
{
   //class content here...
}
like image 43
Davos555 Avatar answered Oct 19 '22 03:10

Davos555