• www.uptuexam.com
  • GBTU Results 2014
  • MTU Results 2014
  • UPTU Circulars
  • COP Result 2012,13,14
  • UPTU Previous Papers
  • GATE study material
  • Robotics Projects
Thank you for visiting www.UPTUexam.com " Free download Exam materials, previous year question papers, free ebooks & Providing Important Questions To Do their Exams Well and Totally a FREE SERVICE for all engineering streams (B.Tech)."

CONSTRUCTOR


CONSTRUCTOR

Ø  It is special member of a class that has following characteristics :
o   It has the same name as of its class.
o   It does not have an explicit return type.
o   It is implicitly invoked just after an object is created.
o   It is used to initialize data members of objects.


Rectangle r = new Rectangle();


1.      Rectangle r;                        //Reference Variable created
2.      r = new Rectangle();          //memory allocation for object

3.      r.Rectangle(5, 4);               //Constructor is invoked

Let’s see it again : 




If a class doesn’t contain any constructor then default constructor is provided by the compiler at the time of compilation but if a class contains any parameterized constructor and there is an object of the class which requires default constructor for its initialization then default constructor need to be defined in the class. In this case, it won’t be provided by the compiler.


·                  javap – to know what is kept in .class file







o   Question: Why compiler provides a default constructor if a class doesn’t contain any constructor and why it doesn’t provide the default constructor when a class contains any parameterized constructor?

o   Solution
§  Overloading – If a class contains multiple implementations of a method or constructor then method or constructor is said to be overloaded.

§  Implementations of overloaded method or constructor are differentiated either by varying the number of arguments or by varying their type of arguments.

§  Overloading is one of the means of implementing polymorphism.


o   Let’s see the advantage of overloading –

  1. PROGRAM Test.java
  2. public class Test
  3. {
  4. public static void main(String[] args)
  5. {
  6. int a = 5;
  7. boolean b = false;
  8. char c = 'A';
  9. System.out.println(a);
  10. System.out.println(b);
  11. System.out.println(c);
  12. }
  13. }


OUTPUT -




  1. class A
  2. {
  3. int a;
  4. public A(int x)
  5. {
  6. a=x;
  7. }
  8. {
  9. System.out.println("It is unusual....");
  10. }
  11. public void display( )
  12. {
  13. System.out.println("a=" +a);
  14. }
  15. public static void main(String[ ] args)
  16. {
  17. A p = new A(10);
  18. A q = new A(20);
  19. p.display();
  20. q.display();
  21. }
  22. }









No comments:

Post a Comment

Google+ Followers