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?
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.
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.
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();
Related
I'm trying to figure out whether implementing individual methods of a subclass in an abstract superclass, or casting is the better way to go about the following scenario.
Suppose I have an abstract class Animal which has two subclasses, Dog and Cat and a Main class where I save objects of Dog and Cat in an Animal array. The following is how I would go about using methods of the subclasses in a more generalized array.
class Main{
public static void main(String[] args){
Animal[] animalArray = new Animal[2];
animalArray[0] = new Cat();
animalArray[1] = new Dog();
for (Animal a : animalArray){
if (a.getClass().equals(Dog.class){
((Dog)a).bark();
} else {
((Cat)a).meow();
}
}
}
}
However a friend suggested that casting isn't best practice, and that I should define each method in the abstract superclass in the following way:
public abstract class Animal{
public abstract String meow(){
return null;
}
public abstract String bark();
return null;
}
}
After setting the return values of these methods to null I would need to use #Override and implement them in the respective subclasses.
Which way is better? I'm afraid the abstract class will be too large and will have methods assigned to subclasses that don't make sense (even if all they do is return null). I think by using casting I can make more precise uses of the methods.
meow() and bark() shouldn't be defined in the Animal class. These methods are specific to Cat and Dog classes.
You should define an abstract method as shown below, in the Animal class and override it in the sub classes.
public abstract class Animal {
public abstract String action() {};
}
public class Dog extends Animal {
#Override
public String action() {
//your implementation (bark)
}
}
public class Cat extends Animal {
#Override
public String action() {
//your implementation (meow)
}
}
Hope it answers your query.
So say, for the purposes of illustration that I have an abstract class Animal, and every Animal has a numberOfLegs.
Dog extends Animal and all dogs have a numberOfLegs of 4.
Is it possible to make numberOfLegs...
Static
Required (everything that extends Animal has to define numberOfLegs, or there is some default value)
Accessible from Animal (this one I'm not as concerned about, but if say the method walk() was called from Dog, could Animal view the number of legs without having to pass an extra value?)
Sorry if this is a strange question, and yes, I understand that I could do this easily in other ways, such as making it an instance variable instead of static, but I'm just kind of curious if there's a better way.
Neither static variables or instance variables participate in polymorphism. Just declare an abstract method, e.g. int getNumberOfLegs(), in the abstract class. Your Dog class could be:
class Dog extends Animal {
private static final int NUMBER_OF_LEGS = 4;
public int getNumberOfLegs () {
return NUMBER_OF_LEGS;
}
}
Is it possible to make numberOfLegs: Static
This would make every instance of a class that extends Animal have the same numberOfLegs. See: here for an explanation.
public abstract class Animal
{
private static int NUMBER_OF_LEGS = 4;
}
Is it possible to make numberOfLegs: Required
Yes, you just have to make a property in the abstract class and initialise it in the constructor.
public abstract class Animal
{
private int numberOfLegs;
public int getNumberOfLegs()
{
return this.numberOfLegs;
}
public Animal(int numberOfLegs)
{
this.numberOfLegs = numberOfLegs;
}
}
public class Zebra extends Animal
{
public Animal(int numberOfLegs)
{
super(numberOfLegs);
}
}
everything that extends Animal has to define numberOfLegs, or there is some default value
Furthermore, if you wanted a default value for number of legs, you could inlcude a constructor for Animal without a numberOfLegs parameter and set it to a value, say 4.
public abstract class Animal
{
private int numberOfLegs;
public Animal()
{
this.numberOfLegs = 4;
}
}
Is it possible to make numberOfLegs: Accessible from Animal
Yes, you can call the method (if it's abstract in the Animal class) from any object that extends Animal
Zebra z = new Zebra(4);
System.out.println(z.getNumberOfLegs());
I have question that is more or less technical. I would like to do the following:
Have a class that will define both a default constructor and another constructor that will create a new object called NamedRunnable.
This class will effectively implement the Runnable interface thus including the run method that it provides.
I want to find a way to no explicitly implement the run method within the the 'NamedRunnable' class itself but have it implemented within all member that will subclass the said class.
Is something like this possible?
If this is something you meant, then yes it is possible :)
public class NamedRunnable implements Runnable {
public NamedRunnable(String name) {
// ....
}
public void run() {
// ...,
}
}
It sounds like you want an abstract class (can't be instantiated) that implements Runnable:
abstract class NamedRunnable implements Runnable {
private String name;
protected NamedRunnable(String _name) {
this.name = _name;
}
}
Note that that doesn't implement run. run is implicitly abstract in that class, as though you had included
abstract public void run();
...because we declare the interface but don't implement it (which we wouldn't be allowed to do if the class weren't declared abtract).
You'd use that as a base class for a concrete class, e.g.:
class Thingy extends NamedRunnable {
public Thingy(String name) {
super(name);
}
#Override
public void run() {
// ...
}
}
The concrete class has the run implementation, and can be instantiated.
I have this abstract base class and each of it's childs should have a specific mandatory function but slightly different. Is this possible using the abstract class or should I be using an interface for this?
I will be using the structure like this
public abstract class Animal
{
//Mandatory method
Public void sound()
{
}
}
public class Cat extends Animal
{
public void sound()
{
System.out.println("Miauw");
}
}
public class Dog extends Animal
{
public void sound()
{
System.out.println("Woof");
}
}
//I will put all these child objects in a List<Animal> and need to call these methods.
for (Animal a : animalList)
{
a.sound();
}
How would one go about this structure? I have to add that I am using an abstract class because there are plenty of identical methods that need to be shared among the child classes. Just some of the methods need to be different from each other but mandatory and accessible from the base class.
You are looking for:
public abstract class Animal
{
//Mandatory method
abstract public void sound();
}
But also look at other users advices:
use lowercase for method names
the keyword publicalways goes in lowercase
use interfaces if your Animal class hasn't common code for all children classes
Both an abstract class and an interface would work in this case. The times when you'd want to use an abstract class is when there are common methods and data that you want shared among all subclasses. Such as, if Animal had a weight variable, and each subclass sets that variable.
NOTE: In an abstract class, any methods that you don't want to implement, you must declare as abstract. See how I modified Sound() below. Also, a bonus tip is that the standards say that method names should start with a lowercase letter, so I changed Sound to sound.
public abstract class Animal
{
private int weight;
public void setWeight(int weight) {
this.weight = weight;
}
public int getWeight() {
return weight;
}
//Mandatory method
abstract public void sound();
}
public class Cat extends Animal
{
public Cat(int weight) {
this.setWeight(weight);
}
public void sound()
{
System.out.println("Miauw");
}
}
public class Dog extends Animal
{
public Dog(int weight) {
this.setWeight(weight);
}
public void sound()
{
System.out.println("Woof");
}
}
You are looking for Java's abstract modifier. The official Java Documentation contains more specific information about abstract and final here.
public abstract class Animal
{
// Mandatory method with no "default" implementation.
public abstract void Sound();
// Optional method with a default implementation.
public void Move() {
// some actions here
}
// Optional method with a fixed implementation (it can't be changed in a child class).
public final void Eat(Food food) {
// some actions here
}
}
you should use interface in this case because you are not defining any method, if you only want to provide declaration interface is ok for that
if you use abstract class you overhead by overriding the method and define it again
How do I create an object of an abstract class and interface? I know we can't instantiate an object of an abstract class directly.
You can not instantiate an abstract class or an interface - you can instantiate one of their subclasses/implementers.
Examples of such a thing are typical in the use of Java Collections.
List<String> stringList = new ArrayList<String>();
You are using the interface type List<T> as the type, but the instance itself is an ArrayList<T>.
To create object of an abstract class just use new just like creating objects of other non abstract classes with just one small difference, as follows:
package com.my.test;
public abstract class MyAbstractClass {
private String name;
public MyAbstractClass(String name)
{
this.name = name;
}
public String getName(){
return this.name;
}
}
package com.my.test;
public class MyTestClass {
public static void main(String [] args)
{
MyAbstractClass ABC = new MyAbstractClass("name") {
};
System.out.println(ABC.getName());
}
}
In the same way You can create an object of interface type, just as follows:
package com.my.test;
public interface MyInterface {
void doSome();
public abstract void go();
}
package com.my.test;
public class MyTestClass {
public static void main(String [] args)
{
MyInterface myInterface = new MyInterface() {
#Override
public void go() {
System.out.println("Go ...");
}
#Override
public void doSome() {
System.out.println("Do ...");
}
};
myInterface.doSome();
myInterface.go();
}
}
There are two ways you can achieve this.
1) Either you extend / implement the Abstract class / interface in a new class, create the object of this new class and then use this object as per your need.
2) The Compiler allows you to create anonymous objects of the interfaces in your code.
For eg. ( new Runnable() { ... } );
Hope this helps.
Regards,
Mahendra Liya.
You can provide an implementation as an anonymous class:
new SomeInterface() {
public void foo(){
// an implementation of an interface method
}
};
Likewise, an anonymous class can extend a parent class instead of implementing an interface (but it can't do both).
public abstract class Foo { public abstract void foo(); }
public interface Bar { public void bar(); }
public class Winner extends Foo implements Bar {
#Override public void foo() { }
#Override public void bar() { }
}
new Winner(); // OK
"instantiate" means "create an object of".
So you can't create one directly.
The purpose of interfaces and abstract classes is to describe the behaviour of some concrete class that implements the interface or extends the abstract class.
A class that implements an interface can be used by other code that only knows about the interface, which helps you to separate responsibilities, and be clear about what you want from the object. (The calling code will only know that the object can do anything specified in the interface; it will not know about any other methods it has.)
If you are using someone else's code that expects a Fooable (where that is the name of some interface), you are not really being asked for an object of some Fooable class (because there isn't really such a class). You are only being asked for an instance of some class that implements Fooable, i.e. which declares that it can do all the things in that interface. In short, something that "can be Foo'd".
You write a class that derives from the abstract class or implements the interface, and then instantiate that.
What you know is correct. You cannot create an object of abstract class or interface since they are incomplete class (interface is not even considered as a class.)
What you can do is to implement a subclass of abstract class which, of course, must not be abstract. For interface, you must create a class which implement the interface and implement bodies of interface methods.
Here are orginal tutorial on oracle site, http://download.oracle.com/javase/tutorial/java/IandI/abstract.html and http://download.oracle.com/javase/tutorial/java/concepts/interface.html
You can not instantiate the abstract class or an interface, but you can instantiate one of their subclasses/implementers.
You can't instantiate an abstract class or an interface, you can only instantiate one of their derived classes.
In your example
MyAbstractClass ABC = new MyAbstractClass("name") {
};
You are instantiating any class that implements Suprising.
public abstract class AbstractClass { ... }
public interface InterfaceClass { ... }
// This is the concrete class that extends the abstract class above and
// implements the interface above. You will have to make sure that you implement
// any abstract methods from the AbstractClass and implement all method definitions
// from the InterfaceClass
public class Foo extends AbstractClass implements InterfaceClass { ... }
NO, we can't create object out of an interface or Abstract class because
Main intention of creating an object is to utilize the wrapped methods and data.
As interface don't have any concrete implementation hence we cannot.
For abstract class we may have concrete method or abstract method or both.
There is no way for the API developer to restrict the use of the method thats don't have implementation.
Hope help.
No, you are not creating the instance of your abstract class here. Rather you are creating an instance of an anonymous subclass of your abstract class. And then you are invoking the method on your abstract class reference pointing to subclass object.