OOPS Flashcards
What are the main principles of Object Oriented Programming?
Abstraction
Encapsulation
Inheritance
Polymorphism
What is the difference between
Object Oriented Programming
language and Object Based
Programming language
Object Oriented Programming languages like Java and C++ follow concepts of OOPS like- Encapsulation, Abstraction, Polymorphism
and Inheritance etc.
Object Based Programming languages follow some features of OOPS but they do not provide support for Polymorphism and Inheritance. Egg. JavaScript, VBScript etc.
.Why do we need constructor in
Java?
A constructor is a special function that has same name as class name.
Without a constructor, there is no other way to create an object.
By default, Java provides a default constructor for every object. If we overload a constructor then we have to implement default constructor.
.Why do we need default constructor in Java classes?(Constructor with no arguments)
Java specification says that it will provide a default constructor if there is no overloaded constructor in a class. But it does not say anything about the scenario in which we write an overloaded constructor in a class.
We need at least one constructor to create an object, that’s why Java provides a default constructor.
When we have overloaded constructor, then Java assumes that we want some custom treatment in our code. Due to which it does not provide default constructor. But it needs default constructor as per
the specification. So it gives error.
What is the value returned by Constructor in Java?
When we call a constructor in Java, it returns the object created by it. That is how we create new objects in Java.
Why constructors cannot be final, static, or abstract in Java?
If we set a method as final it means we do not want any class to override it. But the constructor cannot be overridden. So there is no use of marking it
final.
If we set a method as abstract it means that it has no body and it should be implemented in a child class. But the constructor is called
implicitly when the new keyword is used. Therefore it needs a body.
If we set a method as static it means that it belongs to the class, but not a particular object. The constructor is always called to initialize
an object. Therefore, there is no use of marking constructor static.