- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Can a constructor be synchronized in Java?
- Can a constructor be made final in Java?
- Why a constructor cannot be final in Java?
- Can a constructor throw an exception in Java?
- Can we define a static constructor in Java?
- Can we have a constructor private in java?
- Can constructor throw exceptions in Java?
- Why constructor cannot be final in Java
- Can we declare a constructor as private in Java?
- If a method in parent class “throws Exception”, can we remove it in overridden method in java?
- Can we call a constructor directly from a method in java?
- Can we declare constructor as final in java?
- Can we initialize static variables in a default constructor in Java?
- Where and how can I create a private constructor in Java?
- How do you prevent a method from getting overridden in java?

Advertisements