Showing posts with label Constructor. Show all posts
Showing posts with label Constructor. Show all posts

Wednesday, August 21, 2019

Can we overload constructor in java?

Problem statement:
You are given a code for constructor overloading. What do you think, can we overload the constructor in java?

Ans: Yes.
  1. class A {
  2. A() {
  3. System.out.println("default");
  4. }
  5. A(int id) {
  6. System.out.println("id");
  7. }
  8. A(int id, String name) {
  9. System.out.println("id & name");
  10. }
  11. A(String name, Double salary) {
  12. System.out.println("name & salary");
  13. }
  14. }
  15. public class Sample {
  16. public static void main(String[] args) {
  17. A a = new A();
  18. }
  19. }
Output:
default

Can we override constructor in java?

Problem statement:
You are given a code for constructor overriding. What do you think, can we override the constructor in java?

Ans: No.
  1. class A {
  2. A() {
  3. System.out.println("A of A");
  4. }
  5. }
  6. class B extends A {
  7. A() {
  8. System.out.println("A of B");
  9. }
  10. }
  11. public class Sample {
  12. public static void main(String[] args) {
  13. B b = new B();
  14. }
  15. }
Output:
Return type of method is missing, meaning compiler is treating A() as a method not as a constructor and also compiler is expecting return type for the method A(), because in code there is no return type.

Saturday, April 27, 2019

what is the output of the code?

Problem statement:
Given the code for constructor overloading. What will be the output?
  1. public class ConstructorCall {
  2.     ConstructorCall() {
  3.         System.out.println("default constructor");
  4.     }
  5.     ConstructorCall(int a){
  6.         this();
  7.         System.out.println("parameterized constructor");
  8.         System.out.println(10);
  9.     }
  10.     public static void main(String[] args) {
  11.         ConstructorCall st = new ConstructorCall(3);
  12.     }
  13. }
Output:
default constructor
parameterized constructor
10

Can we have final constructor in java class?

Problem statement:
Can we have final constructor in java class?

No ! we cannot have final constructor in java class.
  1. public class NoFinalConstructor {
  2.     public final NoFinalConstructor() {
  3.         System.out.println("default");
  4.     }
  5.     public static void main(String[] args) {
  6.         NoFinalConstructor st = new NoFinalConstructor();
  7.     }
  8. }
Output: compile time error - modifier 'final' is not allowed.

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...