1

I have a question about abstract classes.

First of all ... I'm using the google translator, sorry :( I hope you understand.

If abstract classes can not be instantiated, exactly, what is this code:

public class Ppal {

public void start(){

    ABS clsAbs = new ABS() {

        @Override
        public void absMetod() {
        }
    };

    clsAbs.metod();
}
}

ABS:

public abstract class ABS{

public void metod(){}
public abstract void absMetod();

}

ABS clsAbs = new ABS () {... Is not this an instance? clsAbs can be used and Abstract classes can not be used, only to create a model of abstraction ...

It could be used as anonymous class but this (ABS clsAbs = new ABS () {...) not anonymous.

Thank you very much in advance!

Aleksandr M
  • 24,264
  • 12
  • 69
  • 143
Marquake
  • 191
  • 1
  • 3
  • 10

2 Answers2

12

You are instantiating an anonymous class that is extending the class ABS. And you can instantiate this anonymous class because it defines all the abstract methods in ABS(Thanks Nebelmann)

It is the same if you create a class like public class Foo extends ABS that implements the absMetod()

and you can do: ABS bar = new Foo()

Renato Lochetti
  • 4,558
  • 3
  • 32
  • 49
  • 2
    And you can instantiate this anonymous class because it defines all the abstract methods in ABS. – Bastien Jansen Jan 22 '13 at 11:05
  • 1
    Understood, I must see ABS clsAbs = new ABS () {... as a normal class that extends another abstract but not as an instance of ABS. If you ask me if an abstract class can be instantiated, I will answer no. Is it correct? – Marquake Jan 22 '13 at 12:03
  • Perfect! You understood the concept. – Renato Lochetti Jan 22 '13 at 12:04
1

All you need to understand is this

ABS clsAbs = new ABS() {

        @Override
        public void absMetod() {
        }
    };

you are implementing the abstract method absMetod() while creating anonymous class that extends ABS class

Bhavik Shah
  • 5,125
  • 3
  • 23
  • 40