Head First Java - Chapter 8 (Serious Polymorphism) - by Harshani Nimanthika - Medium
Head First Java - Chapter 8 (Serious Polymorphism) - by Harshani Nimanthika - Medium
Save
Now, you can see, there are some classes which we should not instantiate.
There is simple way to prevent a class from ever being instantiated.(In other words, to
stop anyone from saying “new” on that type.) That is called “Abstract classes”.
Abstract Class
The class which should not be instantiated!
How we can make Abstract class is, just put ‘abstract’ keyword in your class.
You can still use that abstract type as a reference type.
When you’re designing your class inheritance structure, you have to decide which
classes are abstract and which are concrete.
Abstract vs Concrete
Abstract Class ->An abstract class has virtually no use, no value, no purpose in life,
unless it is extended. With an abstract class, the guys doing the work at runtime are
instances of a subclass of your abstract class.(The compiler won’t let you instantiate an
abstract class)
Concrete Class ->A class that’s not abstract is called a concrete class. That means, we
can create objects from this class.
Abstract Methods
This methods has no body. And the classes which are refer the class should implement
this method. Implementing an abstract method is just like overriding a method.
If you declare an abstract method, you MUST mark the class abstract as well. You
can’t have an abstract method in a non-abstract class.
Polymorphism
‘Polymorphism’ means ‘many forms’.
With polymorphism, the reference type can be a superclass of the actual object type.
Any class that doesn’t explicitly extend another class, implicitly extends Object.
Interface
A Java interface solves your multiple inheritance problem by giving you much of the
polymorphic benefits of multiple inheritance.
The special thing here is Interface is something by default abstract one. And all the
methods inside the interface are abstract ones. So we don’t use abstract keyword in
there for each and every methods. But all the methods are abstract ones.
2. Make a subclass (in other words, extend a class) only when you need to make a
more specific version of a class and need to override or add new behaviors.
3. Use an abstract class when you want to define a template for a group of subclasses,
and you have at least some implementation code that all subclasses could use.
Make the class abstract when you want to guarantee that nobody can make objects
of that type.
4. Use an interface when you want to define a role that other classes can play,
regardless of where those classes are in the inheritance tree.
1 1