Java misc1


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Java misc1

  1. 1. Sem 4 Paper 3 SYIT C++/Java CONSTURCTOR OVERLOADING Program 1: Write a program to demonstrate constructor overloading, with the help of a class called Box, which could either be a rectangle parallelepiped taking in 3 dimensions or a cuboid taking in single dimension, or simply an empty constructor class Box { double length, width, height=0; Box(double x) { length = x; width = x; height = x; } //Similar to copy constructor in C++ Box(Box ob) { width = ob.width; height = ob.height; length = ob.length; } Box() { width = length = height = -1; } Box(double len, double ht, double wd) { length = len; height = ht; width = wd; } double volume() { return(length*width*height); } //class BoxMass inherits all the properties of class // Box class BoxMass extends Box { double mass; // weight of the box BoxMass(double w, double h, double l, double m) { width = w; height = h; length = l; mass = m; } } ----------------------------------------------------------class BoxDemo { public static void main(String args[]) { BoxMass bm1 = new BoxMass(10,20,30,12); BoxMass bm2= new BoxMass(1,2,3,4.4); System.out.println("Volume is:"+bm1.volume()); System.out.println("Mass is:"+bm1.mass); System.out.println("Volume is:"+bm2.volume()); System.out.println("Mass is:"+bm2.mass); } } } /*D:SYITjava_demosinheritance>javac D:SYITjava_demosinheritance>java BoxDemo Volume is:6000.0 Mass is:12.0 Volume is:6.0 Mass is:4.4 */ Compiled by L.Fernandes 1
  2. 2. Sem 4 Paper 3 SYIT C++/Java class ColorBox extends Box { String color; //Inside main function ColorBox(double w, double h, double l, String c) { width = w; height = h; length = l; color = c; } } System.out.println("Volume is:"+cb1.volume()); System.out.println("Color is:"+cb1.color); -----------------------------------------------O/p??????? ColorBox cb1 = new ColorBox(11,11,11,"red"); Box BoxMass ColorBox ----------------------------------------Exercise----------------------------------------Java Language Keywords You cannot use any of the following as identifiers in your programs. The keywords const and goto are reserved, even though they are not currently used. true, false, and null might seem like keywords, but they are actually literals; you cannot use them as identifiers in your programs. abstract *** assert boolean break byte case catch char class const * continue default do double else For * enum extends final finally goto If implements Import instanceof Int interface Long float Native **** new package private protected public return short static strictfp super ** switch synchronized this throw throws transient try void volatile while * not used added in 1.2 *** added in 1.4 **** added in 5.0 [circle out the keywords that you find common in C++] ** Compiled by L.Fernandes 2
  3. 3. Sem 4 Paper 3 SYIT C++/Java Referencing the Subclass Object via the Superclass variable So far you have been studying of how the sub-class object initializes member variables and member methods of Super class through inheritance. In the following program we see how a superclass object can be used to reference a sub-class object. class RefDemo { public static void main(String[] args) { BoxMass massbox = new BoxMass(1,2,3,4.5); Box plainbox = new Box(); double vol; vol = massbox.volume(); System.out.println("Volume is:"+vol); System.out.println("Mass of box:"+massbox.mass); plainbox = massbox; //Assigning the BoxMass reference to Box reference vol = plainbox.volume(); System.out.println("Volume of plainbox is:"+vol); System.out.println("Mass of plainbox is:"+plainbox.mass); //throws error } } Compile time error: D:SYITjava_demosinheritance>javac cannot find symbol symbol : variable mass location: class Box System.out.println("Mass of plainbox is:"+plainbox.mass); ^ 1 error - - - -- --- -- ------------------------------------------------- ------------------------------------1] It is the type of reference variable (here: plainbox) and not the type of object that it refers to-that determines, what members are accessed. 2] Hence when a reference to a sub-class object is assigned to a super-class reference variable, we will have access to only those parts of the object that are defined by the superclass (here length, width, height, volume()) Compiled by L.Fernandes 3
  4. 4. Sem 4 Paper 3 SYIT C++/Java 3] Hence plainbox is unable to access member variable: mass of massbox object even though it refers to BoxMass class. Learning-Super class has no knowledge as to what new specialization a sub class adds to its class, hence mass is not visible and not accessible to Super class reference variable. Practical Application: ---------------------------------------------------------------------------------------------Q] How do we access the Parent class constructor from the Child class? SUPER Notice the constructor in class BoxMass, here even though the first 3 variables are already initialized by parent class Box, yet they are done again. This leads to duplicate code. BoxMass(double w, double h, double l, double m) { It suggests that a subclass needs to be width = w; granted access to superclass members. height = h; length = l; mass = m; } } What if the superclass members are declared as private??????? class Box { private double length, width, height=0; - ---- ---} If this was the case, subclass objects would never be able to access the objects of the parent class. Solution to this problem is keyword super. - Q] What are the two uses of super? - Super has 2 forms= I Calls the superclass’ constructor II Used to access a member of the superclass that has been hidden by a member of a subclass. I] Using super to call Superclass Constructors Super is used to call the constructor of the parent class. Syntax: Super(param-list); Compiled by L.Fernandes 4
  5. 5. Sem 4 Paper 3 SYIT C++/Java 1] The parameter list specifies any parameters that would be required by the constructor in the super class. 2] The Java compiler automatically inserts the necessary constructor calls in the process of constructor chaining, or you can do it explicitly. 3] When a subclass issues a call to super(), it is actually calling the constructor of the immediate superclass above it. 4] super() must always be the first statement executed inside a subclass constructor. Explanation with the help of code: class BoxMass extends Box //class BoxMass inherits all the properties of class Box { double mass; // weight of the box BoxMass(double w, double h, double l, double m) { super(w,h,l); /*width = w; height = h; length = l;*/ mass = m; } } Learning: 1] We managed to achieve data hiding here by declaring length, width and height private. 2] A Sub class need not perform initialization of SuperClass member data, it simply needs to call super to perform this task. Hence, the Subclass can simply be concerned with initialization of its own member variables declared within in its own class. Exercise: Complete program 1 by implementing all constructor calls within class BoxMass with the help of super. Code snippet: BoxMass() class BoxMass extends Box { { super(); // super here calls the double mass; // weight of the box empty constructor of class Box mass = -1; BoxMass(double l, double w, double h, double m) } { BoxMass(double x, double m) super(l,w,h); { mass = m; super(x); } mass = m; BoxMass(BoxMass obj) } { } super(obj); mass = obj.mass; } Compiled by L.Fernandes 5
  6. 6. Sem 4 Paper 3 SYIT C++/Java II] Used to access a member of the SuperClass that has been hidden by a member of a subclass. [Before delving into the topic a quick introduction to the “this” keyword] Q] Explain the keyword: this this: Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. It is possible to refer to any member of the current object from within an instance method or a constructor by using the keyword this. > Using this with a member field: The following is an example of how “this” can be used with a field Q] What is shadowing (Instance variable hiding)? class Triangle { double base; double height; Triangle(double b, double h) //constructor { base = b; height = h; } double area() { double f=1/2d; return(base*height*f); } } class TriangleDemo { public static void main(String[] args) { Triangle t1 = new Triangle(20,30); System.out.println("Area is:"+t1.area()); } } D:SYITjava_demosinheritance>java TriangleDemo Area is:300.0 Compiled by L.Fernandes Triangle(double base,double height) //constructor { base = base; height = height; } • Disadvantage:The above code would not take in the value 20 and 30 but it would print the area as 0.0, as 0 is the default value of base and height. • Advantage: here is that we are not declaring new variables b and h but reusing the same variable base and height Triangle(double base,double height)//constructor { this.base = base; this.height = height; } Learning: Each argument to the constructor shadows the object's fields — inside the constructor base is a local copy of the constructor's first argument. In order to refer to the Triangle field base, the constructor must use this.base. Output: Area is:300.0 6
  7. 7. Sem 4 Paper 3 SYIT C++/Java Using this with a Constructor: The “this” keyword could be used from within a constructor to call another constructor. The following is an example of how “this” can be used to call another constructor class Triangle { double base; double height; Triangle() { //no- argument constructor calls 2-argument constructor this(0,0); } } //end of class Triangle(double base,double height) { this.base = base; this.height = height; } Triangle(double base) { //Explicit constructor invocation this(base,0); } double area() { double f=1/2d; return(base*height*f); } class TriangleDemo { public static void main(String[] args) { Triangle t1 = new Triangle(20,30); Triangle t2 = new Triangle(20); System.out.println("Area of t1 is:"+t1.area()); System.out.println("Area of t2 is:"+t2.area()); } }//end of class Output: 1. A class may contain several constructors, each initializing all or just a few member fields. 2. The compiler determines which constructor to call, based on the number and the type of arguments. 3. If a value is not provided, then the constructor must initialize it with a default value, which is not provided by the argument. 4. The invocation of another constructor must be the first line in the constructor, i.e. “this” should be the first line of code within the constructor. Thinking Cap: What will happen if we type : Triangle(double base) { this(base); } Will there be an error? What would the error be? What concept does this remind you of? Compiled by L.Fernandes instead of: Triangle(double base) { this(base,0); } 7
  8. 8. Sem 4 Paper 3 SYIT Coming back to the second use of Super C++/Java The second form of super acts similar to “this”. 1] It always refers to the SuperClass of the SubClass in which it is used. Syntax: super.member Where, member can be either an instance variable or a method. 2] super can also be used for hiding members just the way “this” is used. Super is most applicable to situations in which member names of a subclass hide members by the same name in the SuperClass. 3] Super can also be used to call methods of the SuperClass that are hidden by the SubClass. Explanation of the concept with the help of an example: class SuperDemo class ASuperClass { { public static void main(String[] args) int i; { } ASubClass obj = new ASubClass(100,11); class ASubClass extends ASuperClass obj.show_fields(); } { int i; // this is hiding the i of the super class } ---------------------------------------------/*D:SYITjava_demosinheritance>java ASubClass(int a, int b) { SuperDemo i in ASuperClass : 100 super.i=a; // i in ASuperClass i in ASubClass : 11*/ i=b; // i in ASubClass } void show_fields() { System.out.println("i in ASuperClass : "+super.i); System.out.println("i in ASubClass : "+i); } } In the above program the field “ i ” is common in both the Super class as well as the Sub class, the sub class hides the field i of the super class, this value can be obtained with the help of super. Q] Is super a keyword? -------------------------**************************************---------------------------------- Compiled by L.Fernandes 8