0

I have a abstract class about crawler:

public abstract class AbstractCrawler {
    public AbstractCrawler(){
        initialize();
    }
    protected abstract void initialize();
    protected abstract void work();
    protected abstract void saveAndUpdate(Object obj);
}

As you can see,abstract method of "saveAndUpdate" needs the param of Object,Because,each crawler extends this abstract will save or update different data type,like this:

public class UserCrawler extends AbstractCrawler{
    @Override
    protected void saveAndUpdate(List<User> obj) {
        // TODO Auto-generated method stub

    }
}

and class of CommentCrawler:

public class CommentCrawler extends AbstractCrawler{
        @Override
        protected void saveAndUpdate(List<Comment> obj) {
            // TODO Auto-generated method stub

        }
}

It's pretty obvious, just do something like this.Making abstract class more concise.

v11
  • 2,124
  • 7
  • 26
  • 54
  • 1
    Use generics `public abstract class AbstractCrawle {` and then `protected abstract void saveAndUpdate(T obj)`.... – MadProgrammer Oct 17 '14 at 01:38
  • [Be careful.](http://stackoverflow.com/questions/18138397/calling-method-from-constructor) – Sotirios Delimanolis Oct 17 '14 at 01:39
  • @MadProgrammer But oher programmers don't know what T is,they just want to use the function of class by public method.how about Use Object and doing converte in the subclass method of "saveAndUpdate". – v11 Oct 17 '14 at 01:45
  • That's the point `T` is generic, in order to work with it, they need to define it... – MadProgrammer Oct 17 '14 at 01:46

1 Answers1

4

You could use the inbuilt generics support, for example...

public abstract class AbstractCrawler<T> {
    public AbstractCrawler(){
        initialize();
    }
    protected abstract void initialize();
    protected abstract void work();
    protected abstract void saveAndUpdate(T obj);
}

This allows implementations to specify the type of data they are expecting to work with...

public class CommentCrawler extends AbstractCrawler<List<Comment>> {
    @Override
    protected void saveAndUpdate(List<Comment> obj) {
        //....
    }

    //...
}

Also, be careful calling methods from constructors, what the method might rely on might not have yet been initialized.

Have a look at Lesson: Generics for more details...

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366