Reputation: 327
I have an abstract class that extends a concrete class. But I'm confused about how to use it. How am I supposed 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?
Upvotes: 6
Views: 20450
Reputation: 1014
For example, let’s say we have an abstract class, Foo, extending the 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();
Upvotes: 2
Reputation: 279
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.
Upvotes: 5
Reputation: 21912
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.
Upvotes: 22