0% found this document useful (0 votes)
29 views8 pages

Unit-II Constructors

The document explains the concept of constructors in Java, detailing their purpose, types (default and parameterized), and rules for creation. It also covers inheritance, including how classes can inherit from one another, member access, and the use of the 'super' keyword to reference superclass members and constructors. Examples illustrate the implementation of constructors and inheritance in Java programming.

Uploaded by

Suja Mary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views8 pages

Unit-II Constructors

The document explains the concept of constructors in Java, detailing their purpose, types (default and parameterized), and rules for creation. It also covers inheritance, including how classes can inherit from one another, member access, and the use of the 'super' keyword to reference superclass members and constructors. Examples illustrate the implementation of constructors and inheritance in Java programming.

Uploaded by

Suja Mary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Unit-II

Constructors
 A constructor initializes an object immediately upon creation.
 It has the same name as the class in which it resides and is syntactically similar to a
method.
 Once defined, the constructor is automatically called immediately after the object is
created, before the new operator completes.
 Constructors look a little strange because they have no return type, not even void. This is
because the implicit return type of a class’ constructor is the class type itself
Example
/* Here, Box uses a constructor to initialize the dimensions of a box. */
Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
} // compute and return volume
double volume() {
return width * height * depth;
}}
BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol; // get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume();
System.out.println("Volume is " + vol);
}}
When this program is run, it generates the following results:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
To allocate an object, the general form is:
class-var = new classname( );
Thus, in the line Box
mybox1 = new Box();
new Box( ) is calling the Box( ) constructor.
Rules for creating Java constructor
There are two rules defned for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, fnal, and synchronized

Types of Constructor
1. Default Constructors
2. Parameterized Constructors
Default Constructors
 A constructor is called "Default Constructor" when it doesn't have any parameter.
 The default constructor automatically initializes all instance variables to zero.
 The default constructor is often sufficient for simple classes, but it usually won’t do for
more sophisticated ones.
 Once we define our own constructor, the default constructor is no longer used.
Syntax of default constructor:
Classname(){}
Example
Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
width = 10;
height = 10;
depth = 10;
}
Parameterized Constructors
A constructor which has a specific number of parameters is called a parameterized constructor.
Example
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}}
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);

Inheritance
 Inheritance is one of the cornerstones of object-oriented programming because it allows
the creation of hierarchical classifications.
 Class can then be inherited by other, more specific classes, each adding those things that
are unique to it.
 A class that is inherited is called a superclass.
 The class that does the inheriting is called a subclass.
Inheritance Basics
To inherit a class, the definition of one class into another by using the extends keyword
Example
// A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}}
The program creates a superclass called A and a subclass called B.
The keyword extends is used to create a subclass of A.
The subclass B includes all of the members of its superclass, A. The subOb can access i and j
and call showij( ).

The general form of a class declaration that inherits a superclass is shown here:
class subclass-name extends superclass-name {
// body of class
}
 One superclass for any subclass that we can create.
 Java does not support the inheritance of multiple superclasses into a single subclass.
 Create a hierarchy of inheritance in which a subclass becomes a superclass of another
subclass.
Member Access and Inheritance
Although a subclass includes all of the members of its superclass, it cannot access those
members of the superclass that have been declared as private.
Example
// Create a superclass.
class A {
int i; // public by default
private int j; // private to A
void setij(int x, int y) {
i = x;
j = y;
}}
// A's j is not accessible here.
class B extends A {
int total;
void sum() {
total = i + j;
// ERROR, j is not accessible here
}}
This program will not compile because the reference to j inside the sum( ) method of B causes an
access violation. Since j is declared as private, it is only accessible by other members of its own
class. Subclasses have no access to it.
A major advantage of inheritance is that once you have created a superclass that defines the
attributes common to a set of objects, it can be used to create any number of more specific
subclasses. Each subclass can precisely tailor its own classification.

A Superclass Variable Can Reference a Subclass

Object A reference variable of a superclass can be assigned a reference to any subclass derived
from that superclass.

Example
class RefDemo {
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box();
double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " + weightbox.weight);
System.out.println();
// assign BoxWeight reference to Box reference
plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox does not define a weight member. */ //
System.out.println("Weight of plainbox is " + plainbox.weight);
}}
Here, weightbox is a reference to BoxWeight objects, and plainbox is a reference to Box objects.
Since BoxWeight is a subclass of Box, it is permissible to assign plainbox a reference to the
weightbox object.

When a reference to a subclass object is assigned to a superclass reference variable, you will
have access only to those parts of the object defined by the superclass.

Using super
A subclass needs to refer to its immediate superclass, it can do so by use of the keyword super.

super has two general forms.

 The first calls the superclass’ constructor.


 The second is used to access a member of the superclass that has been hidden by a
member of a subclass.
Using super to Call Superclass Constructors

A subclass can call a constructor defined by its superclass by use of the following form of super:

super(arg-list);

Here, arg-list specifies any arguments needed by the constructor in the superclass.

super( ) must always be the first statement executed inside a subclass’ constructor.
// BoxWeight now uses super to initialize its Box attributes
class BoxWeight extends Box {
double weight; // weight of box
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}}
Here, BoxWeight( ) calls super( ) with the arguments w, h, and d. This causes the Box( )
constructor to be called, which initializes width, height, and depth using these values.
BoxWeight no longer initializes these values itself. It only needs to initialize the value unique to
it weight. This leaves Box free to make these values private if desired.

A Second Use for super

The second form of super acts somewhat like this, except that it always refers to the
superclass of the subclass in which it is used. This usage has the following general form:

super.member
Here, member can be either a method or an instance variable. This second form of super
is most applicable to situations in which member names of a subclass hide members by the same
name in the superclass. Consider this simple class hierarchy:
// Using super to overcome name hiding.
class A {
int i;
}
// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}}
The instance variable i in B hides the i in A, super allows access to the i defined in the
superclass.
Creating a Multilevel Hierarchy
Simple class hierarchies that consist of only a superclass and a subclass.
To build hierarchies that contain as many layers of inheritance. It is perfectly acceptable to use a
subclass as a superclass of another.
Example
Given three classes called A, B, and C, C can be a subclass of B, which is a subclass of A. When
this type of situation occurs, each subclass inherits all of the traits found in all of its superclasses.
// Extend BoxWeight to include shipping costs.
// Start with Box.
class Box {
private double width;
private double height;
private double depth;
// construct clone of an object
Box(Box ob) {
// pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
} // constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}}
class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) {
// pass object to constructor
super(ob);
weight = ob.weight;
} // constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}}
class Shipment extends BoxWeight {
double cost; // construct clone of an object
Shipment(Shipment ob) {
// pass object to constructor
super(ob);
cost = ob.cost;
} // constructor when all parameters are specified
Shipment(double w, double h, double d, double m, double c) {
super(w, h, d, m); // call superclass constructor
cost = c;
}
Because of inheritance, Shipment can make use of the previously defined classes of Box and
BoxWeight, adding only the extra information it needs for its own, specific application. This is
part of the value of inheritance; it allows the reuse of code.

You might also like