Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract Class Extending Concrete Classes

I have an abstract class that extends a concrete class. But I'm confused about how to use it. How am I suppose to instantiate the concrete class with the methods in the abstract class like I would normally do the other way around? Or is there another way to instantiate the classes?

like image 467
Eddie White Avatar asked Nov 12 '15 22:11

Eddie White


3 Answers

An abstract class always extends a concrete class (java.lang.Object at the very least). So it works the same as it always does. If you want to instantiate it, you will have to subclass it with a concrete implementation of those abstract methods and instantiate it through the concrete class.

Just like you always do. This isn't a special case.

like image 75
mprivat Avatar answered Oct 19 '22 15:10

mprivat


You can have a sort of implementation. What I mean by this is like: Let's say you have an Animal class. The Animal class has a method names jump() and then another class that extends Mammal. The Mammal class is abstract. What my understanding is that you would like whatever class extends Mammal to HAVE to override the jump() method. This is what I believe is your question. To achieve this, I would say to create an abstract method and call that in the original method. What I mean by this is like so:

public class Animal
{
    public final String name;
    public final int weight;

    public Animal(String name, int weight)
    {
        this.name = name;
        this.weight = weight;
    }

    public void jump()
    {
        System.out.println(name + " Jumped");
    }
}

Then you have the Mammal class:

public abstract class Mammal extends Animal
{
    public Mammal(String name, int weight)
    {
        super(name, weight);
    }

    public abstract void jumpMammal();

    @Override
    public final void jump()
    {
        jumpMammal();
    }
}

If any class attempts to override the Mammal class, they are required to override the jumpMammal() method, therefore running in the jump() method.

like image 37
Hashim Kayani Avatar answered Oct 19 '22 13:10

Hashim Kayani


for example lets say we have a foo abstract class extending fooFather class .

public abstract class Foo extends FooFather{



}

then we create a subclass that extends Foo like this:

public class Foo2 extends Foo{



}

And initialize it like this

Foo aFoo=new Foo2();
like image 32
cssGEEK Avatar answered Oct 19 '22 15:10

cssGEEK