- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can a constructor be overridden in java?
If super class and sub class have same methods including name, return type and parameters, and if you try to call it using the object of the sub class
Then the method in the sub class is invoked.
Constructor looks like method but it is not. It does not have a return type and its name is same as the class name.
But, a constructor cannot be overridden. If you try to write a super class’s constructor in the sub class compiler treats it as a method and expects a return type and generates a compile time error.
Example
class DemoTest{ DemoTest(){ System.out.println("This is the constructor of the demo class"); } } public class OverridingConstructor extends DemoTest { DemoTest(){ System.out.println("This is the constructor of the demo class"); } }
Output
C:\Sample>javac Example.java Example.java:2: error: class Sample is public, should be declared in a file named Sample.java public class Sample { ^ 1 error
Advertisements