SlideShare a Scribd company logo
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 BoxDemo.java
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

lydia_fdes@yahoo.co.in

1
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

lydia_fdes@yahoo.co.in

2
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 RefDemo.java
RefDemo.java:23: 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

lydia_fdes@yahoo.co.in

3
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

lydia_fdes@yahoo.co.in

4
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

lydia_fdes@yahoo.co.in

5
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

lydia_fdes@yahoo.co.in

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
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

lydia_fdes@yahoo.co.in

instead of:
Triangle(double base)
{
this(base,0);
}

7
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

lydia_fdes@yahoo.co.in

8

More Related Content

PDF
Java 1-contd
PPT
JAVA CONCEPTS
PPT
Spsl v unit - final
PPTX
SQL Server Select Topics
PPTX
Cassandra
PPTX
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
PPTX
Python 3.6 Features 20161207
Java 1-contd
JAVA CONCEPTS
Spsl v unit - final
SQL Server Select Topics
Cassandra
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
Python 3.6 Features 20161207

What's hot (20)

PPTX
Unit 1 - R Programming (Part 2).pptx
PPT
Executing Sql Commands
PDF
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
PDF
0php 5-online-cheat-sheet-v1-3
ODP
Python Day1
PPT
Oop lecture9 13
PDF
PT- Oracle session01
PDF
Learn a language : LISP
PDF
Using Scala Slick at FortyTwo
PDF
Object oriented programming
PDF
Php Map Script Class Reference
PPTX
Basic sql Commands
PPTX
Classes and objects1
PPTX
Breaking down data silos with the open data protocol
PPT
Class & Object - User Defined Method
PPTX
Chapter 6.6
DOC
PPTX
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
PPTX
SQL commands
Unit 1 - R Programming (Part 2).pptx
Executing Sql Commands
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
0php 5-online-cheat-sheet-v1-3
Python Day1
Oop lecture9 13
PT- Oracle session01
Learn a language : LISP
Using Scala Slick at FortyTwo
Object oriented programming
Php Map Script Class Reference
Basic sql Commands
Classes and objects1
Breaking down data silos with the open data protocol
Class & Object - User Defined Method
Chapter 6.6
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
SQL commands
Ad

Viewers also liked (18)

PDF
Java chapter 6 - Arrays -syntax and use
PDF
Java chapter 5
PDF
Java chapter 1
PDF
Python reading and writing files
PDF
PDF
Digital signal and image processing FAQ
PDF
Java chapter 3
PDF
Java swing 1
PDF
Phases of the Compiler - Systems Programming
DOCX
Python - Regular Expressions
PDF
Html graphics
PDF
Html tables examples
PDF
Java chapter 3 - OOPs concepts
PDF
Data Link Layer
PDF
Data communications ch 1
PDF
Chap 3 data and signals
PPT
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
PDF
Introduction to systems programming
Java chapter 6 - Arrays -syntax and use
Java chapter 5
Java chapter 1
Python reading and writing files
Digital signal and image processing FAQ
Java chapter 3
Java swing 1
Phases of the Compiler - Systems Programming
Python - Regular Expressions
Html graphics
Html tables examples
Java chapter 3 - OOPs concepts
Data Link Layer
Data communications ch 1
Chap 3 data and signals
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Introduction to systems programming
Ad

Similar to Java misc1 (20)

PDF
Class notes(week 6) on inheritance and multiple inheritance
PPT
6.INHERITANCE.ppt(MB).ppt .
DOCX
Class notes(week 6) on inheritance and multiple inheritance
PPTX
Ppt on this and super keyword
PPTX
Inheritance
PDF
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
PDF
Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdf
PDF
Java unit2
PPTX
Class and object
PPTX
JAVA Module 2____________________--.pptx
PPTX
JAVA Module 2 ppt on classes and objects and along with examples
PPTX
Multiple file programs, inheritance, templates
PPT
Java inheritance
PPTX
Class object method constructors in java
PPTX
OOP C++
PPTX
class object.pptx
ODP
Ppt of c++ vs c#
PPTX
Mpl 9 oop
PPT
5.CLASSES.ppt(MB)2022.ppt .
PPTX
Chapter 2 OOP using C++ (Introduction).pptx
Class notes(week 6) on inheritance and multiple inheritance
6.INHERITANCE.ppt(MB).ppt .
Class notes(week 6) on inheritance and multiple inheritance
Ppt on this and super keyword
Inheritance
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdf
Java unit2
Class and object
JAVA Module 2____________________--.pptx
JAVA Module 2 ppt on classes and objects and along with examples
Multiple file programs, inheritance, templates
Java inheritance
Class object method constructors in java
OOP C++
class object.pptx
Ppt of c++ vs c#
Mpl 9 oop
5.CLASSES.ppt(MB)2022.ppt .
Chapter 2 OOP using C++ (Introduction).pptx

More from Mukesh Tekwani (20)

PDF
The Elphinstonian 1988-College Building Centenary Number (2).pdf
PPSX
Circular motion
PPSX
Gravitation
PDF
ISCE-Class 12-Question Bank - Electrostatics - Physics
PPTX
Hexadecimal to binary conversion
PPTX
Hexadecimal to decimal conversion
PPTX
Hexadecimal to octal conversion
PPTX
Gray code to binary conversion
PPTX
What is Gray Code?
PPSX
Decimal to Binary conversion
PDF
Video Lectures for IGCSE Physics 2020-21
PDF
Refraction and dispersion of light through a prism
PDF
Refraction of light at a plane surface
PDF
Spherical mirrors
PDF
Atom, origin of spectra Bohr's theory of hydrogen atom
PDF
Refraction of light at spherical surfaces of lenses
PDF
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
PPSX
Cyber Laws
PPSX
Social media
The Elphinstonian 1988-College Building Centenary Number (2).pdf
Circular motion
Gravitation
ISCE-Class 12-Question Bank - Electrostatics - Physics
Hexadecimal to binary conversion
Hexadecimal to decimal conversion
Hexadecimal to octal conversion
Gray code to binary conversion
What is Gray Code?
Decimal to Binary conversion
Video Lectures for IGCSE Physics 2020-21
Refraction and dispersion of light through a prism
Refraction of light at a plane surface
Spherical mirrors
Atom, origin of spectra Bohr's theory of hydrogen atom
Refraction of light at spherical surfaces of lenses
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Cyber Laws
Social media

Recently uploaded (20)

PPTX
Cell Structure & Organelles in detailed.
PPTX
master seminar digital applications in india
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Classroom Observation Tools for Teachers
PPTX
Pharma ospi slides which help in ospi learning
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Pre independence Education in Inndia.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Cell Types and Its function , kingdom of life
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
VCE English Exam - Section C Student Revision Booklet
Cell Structure & Organelles in detailed.
master seminar digital applications in india
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Classroom Observation Tools for Teachers
Pharma ospi slides which help in ospi learning
2.FourierTransform-ShortQuestionswithAnswers.pdf
Pre independence Education in Inndia.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
GDM (1) (1).pptx small presentation for students
Cell Types and Its function , kingdom of life
Anesthesia in Laparoscopic Surgery in India
Renaissance Architecture: A Journey from Faith to Humanism
PPH.pptx obstetrics and gynecology in nursing
Abdominal Access Techniques with Prof. Dr. R K Mishra
VCE English Exam - Section C Student Revision Booklet

Java misc1

  • 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 BoxDemo.java 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 lydia_fdes@yahoo.co.in 1
  • 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 lydia_fdes@yahoo.co.in 2
  • 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 RefDemo.java RefDemo.java:23: 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 lydia_fdes@yahoo.co.in 3
  • 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 lydia_fdes@yahoo.co.in 4
  • 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 lydia_fdes@yahoo.co.in 5
  • 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 lydia_fdes@yahoo.co.in 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. 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 lydia_fdes@yahoo.co.in instead of: Triangle(double base) { this(base,0); } 7
  • 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 lydia_fdes@yahoo.co.in 8