SlideShare a Scribd company logo
1 of 8
Download to read offline
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

What's hot

Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsphanleson
 
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn Sagar Arlekar
 
0php 5-online-cheat-sheet-v1-3
0php 5-online-cheat-sheet-v1-30php 5-online-cheat-sheet-v1-3
0php 5-online-cheat-sheet-v1-3Fafah Ranaivo
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISPDevnology
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwoEishay Smith
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingRenas Rekany
 
Php Map Script Class Reference
Php Map Script Class ReferencePhp Map Script Class Reference
Php Map Script Class ReferenceJoel Mamani Lopez
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1Vineeta Garg
 
Breaking down data silos with the open data protocol
Breaking down data silos with the open data protocolBreaking down data silos with the open data protocol
Breaking down data silos with the open data protocolWoodruff Solutions LLC
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined MethodPRN USM
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6sotlsoc
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Abu Saleh
 

What's hot (20)

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

Viewers also liked

Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useMukesh Tekwani
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing filesMukesh Tekwani
 
Digital signal and image processing FAQ
Digital signal and image processing FAQDigital signal and image processing FAQ
Digital signal and image processing FAQMukesh Tekwani
 
Phases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingPhases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingMukesh Tekwani
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular ExpressionsMukesh Tekwani
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsMukesh Tekwani
 
Data communications ch 1
Data communications   ch 1Data communications   ch 1
Data communications ch 1Mukesh Tekwani
 
Chap 3 data and signals
Chap 3 data and signalsChap 3 data and signals
Chap 3 data and signalsMukesh Tekwani
 
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferChapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferWayne Jones Jnr
 
Introduction to systems programming
Introduction to systems programmingIntroduction to systems programming
Introduction to systems programmingMukesh Tekwani
 

Viewers also liked (18)

Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing files
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Digital signal and image processing FAQ
Digital signal and image processing FAQDigital signal and image processing FAQ
Digital signal and image processing FAQ
 
Java chapter 3
Java   chapter 3Java   chapter 3
Java chapter 3
 
Java swing 1
Java swing 1Java swing 1
Java swing 1
 
Phases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingPhases of the Compiler - Systems Programming
Phases of the Compiler - Systems Programming
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular Expressions
 
Html graphics
Html graphicsHtml graphics
Html graphics
 
Html tables examples
Html tables   examplesHtml tables   examples
Html tables examples
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs concepts
 
Data Link Layer
Data Link Layer Data Link Layer
Data Link Layer
 
Data communications ch 1
Data communications   ch 1Data communications   ch 1
Data communications ch 1
 
Chap 3 data and signals
Chap 3 data and signalsChap 3 data and signals
Chap 3 data and signals
 
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferChapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
 
Introduction to systems programming
Introduction to systems programmingIntroduction to systems programming
Introduction to systems programming
 

Similar to Java misc1

Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceKuntal Bhowmick
 
6.INHERITANCE.ppt(MB).ppt .
6.INHERITANCE.ppt(MB).ppt                    .6.INHERITANCE.ppt(MB).ppt                    .
6.INHERITANCE.ppt(MB).ppt .happycocoman
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceKuntal Bhowmick
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keywordtanu_jaswal
 
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdfJava-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdfkakarthik685
 
Multiple file programs, inheritance, templates
Multiple file programs, inheritance, templatesMultiple file programs, inheritance, templates
Multiple file programs, inheritance, templatesSyed Zaid Irshad
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in javaRaja Sekhar
 
Mpl 9 oop
Mpl 9 oopMpl 9 oop
Mpl 9 oopAHHAAH
 
5.CLASSES.ppt(MB)2022.ppt .
5.CLASSES.ppt(MB)2022.ppt                       .5.CLASSES.ppt(MB)2022.ppt                       .
5.CLASSES.ppt(MB)2022.ppt .happycocoman
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.pptEmanAsem4
 

Similar to Java misc1 (20)

Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
 
6.INHERITANCE.ppt(MB).ppt .
6.INHERITANCE.ppt(MB).ppt                    .6.INHERITANCE.ppt(MB).ppt                    .
6.INHERITANCE.ppt(MB).ppt .
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
Inheritance
Inheritance Inheritance
Inheritance
 
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdfJava-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
 
Java unit2
Java unit2Java unit2
Java unit2
 
Class and object
Class and objectClass and object
Class and object
 
Multiple file programs, inheritance, templates
Multiple file programs, inheritance, templatesMultiple file programs, inheritance, templates
Multiple file programs, inheritance, templates
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
OOP C++
OOP C++OOP C++
OOP C++
 
class object.pptx
class object.pptxclass object.pptx
class object.pptx
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
Mpl 9 oop
Mpl 9 oopMpl 9 oop
Mpl 9 oop
 
5.CLASSES.ppt(MB)2022.ppt .
5.CLASSES.ppt(MB)2022.ppt                       .5.CLASSES.ppt(MB)2022.ppt                       .
5.CLASSES.ppt(MB)2022.ppt .
 
Second chapter-java
Second chapter-javaSecond chapter-java
Second chapter-java
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
10. inheritance
10. inheritance10. inheritance
10. inheritance
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 

More from Mukesh Tekwani

ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversionMukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversionMukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prismMukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surfaceMukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomMukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesMukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEMukesh Tekwani
 
TCP-IP Reference Model
TCP-IP Reference ModelTCP-IP Reference Model
TCP-IP Reference ModelMukesh Tekwani
 

More from Mukesh Tekwani (20)

Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 
Social media
Social mediaSocial media
Social media
 
TCP-IP Reference Model
TCP-IP Reference ModelTCP-IP Reference Model
TCP-IP Reference Model
 

Recently uploaded

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxleah joy valeriano
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 

Recently uploaded (20)

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 

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