Core Java Interview Questions and Answers
Ques. What is abstraction?Ans. something which is not concrete , something which is imcomplete.
java has concept of abstract classes , abstract method but a variable can not be abstract.
an abstract class is something which is incomplete and you can not create instance of it for using it.if you want to use it you need to make it complete by extending it.
an abstract method in java doesn't have body , its just a declaration.
so when do you use abstraction ? ( most important in my view )
when I know something needs to be there but I am not sure how exactly it should look like.
e.g. when I am creating a class called Vehicle, I know there should be methods like start() and Stop() but don't know start and stop mechanism of every vehicle since they could have different start and stop mechanism e..g some can be started by kick or some can be by pressing buttons .
the same concept apply to interface also , which we will discuss in some other post.
so implementation of those start() and stop() methods should be left to there concrete implementation e.g. Scooter , MotorBike , Car etc.
In Java Interface is an another way of providing abstraction, Interfaces are by default abstract and only contains public static final constant or abstract methods. Its very common interview question is that where should we use abstract class and where should we use Java Interfaces in my view this is important to understand to design better java application, you can go for java interface if you only know the name of methods your class should have e.g. for Server it should have start() and stop() method but we don't know how exactly these start and stop method will work. if you know some of the behavior while designing class and that would remain common across all subclasses add that into abstract class.
1) Use abstraction if you know something needs to be in class but implementation of that varies.
2) In Java you can not create instance of abstract class , its compiler error.
3) abstract is a keyword in java.
4) a class automatically becomes abstract class when any of its method declared as abstract.
5) abstract method doesn't have method body.
6) variable can not be made abstract , its only behavior or methods which would be abstract.
Is it helpful? Yes No
Most helpful rated by users:
- How could Java classes direct program messages to the system console, but error messages, say to a file?
- What are the differences between an interface and an abstract class?
- Why would you use a synchronized block vs. synchronized method?
- How can you force garbage collection?
- When should I use abstract methods?