Search code examples
javaabstract-class

If an abstract class can't be instantiated, why is the following possible?


In the following code a Graphics object is passed into the following paintComponent method, which is then cast into a Graphics2D object. Isn't Graphics an abstract class so why is the following possible?

 public void paintComponent(Graphics comp) {
 Graphics2D comp2D = (Graphics2D) comp;
 Font font = new Font("Comic Sans", Font.BOLD, 15);
 comp2D.setFont(font);
 comp2D.drawString("Potrzebie!", 5, 50);
}

Solution

  • Just because a class can't be instantiated doesn't mean you can't get an instance of it.

    In your example, all you are doing is casting it to a different class which is in the Graphics hierarchy.

    Here's an example.

    
        public class AbstractDemo {
    
           public static void main(String[] args) {
              Concrete c = new Concrete();
              AClass a = (AClass) c;
              a.me();
           }
    
        }
    
        abstract class AClass {
           public void me() {
              System.out.println("Abstract parent");
           }
        }
    
        class Concrete extends AClass {
    
        }