Abstract vs Constructor | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite

Abstract vs Constructor

What is the use of abstract, I mean if in the example we don't create the abstract class and remove the inheritance from cat class. The output will be the same. And how the abstract being used, It not clear enough to me.

14th Jan 2017, 4:30 PM
Ashish Kumar Singh
Ashish Kumar Singh - avatar
2 Réponses
+ 1
Say you have some classes that read stuff from various sources. class File{ public String readLine(){ ... } } class Email{ public String readLine(){ ... } } class Console{ public String readLine(){ ... } } Now, say you also want to add a method called `readAll` that reads the entire File/Email/Console output. It'd look something like this: public String readAll(){ String s = "", line; while((line = readLine()) != null) s += line; return s; } Now - you could add that method to all three classes, but that's kind of ugly. Also notice how `readAll` doesn't really care about what class it is in, all it needs is a method called `readLine`. Abstract classes to the rescue! We can offload that into a Reader class which the others inherit from. public abstract class Reader{ public String readAll(){ /* see above */ } public abstract String readLine(); } class File : Reader{ ... } class Email : Reader{ ... } class Console : Reader{ ... } Now, all the classes have the `readAll`-method, but we only had to write it once. Reader needs to be abstract so we can't instantiate it, since it can't do anything on it's own. Reader also defined `readLine` as abstract, which means the subclasses will need to implement it.
14th Jan 2017, 4:59 PM
Schindlabua - avatar
It is not the concept for Inheritance, that we can define method in readAll() method in super class and then call in sub class. Although, we have to implement readLine()method in sub class only. What difference does it make using abstract class?
16th Jan 2017, 6:37 PM
Ashish Kumar Singh
Ashish Kumar Singh - avatar