Home | Java - Using super

Chapter: Web or internet Programming : JAVA

Java - Using super

There will be times when you will want to create a superclass that keeps the details of its implementation to itself (that is, that keeps its data members private).

Using super

 

There will be times when you will want to create a superclass that keeps the details of its implementation to itself (that is, that keeps its data members private). In this case, there would be no way for a subclass to directly access or initialize these variables on its own. Whenever 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.

 

 

class box2{

 

//  this is the base class , here its member variables are private.hece its //visibility is with in this class alone.

 

private double height; private double depth; private double width;

 

//   use of this operator & this constructor will be called when 3 dimensions //are known

 

box2(double w, double d, double h){ this.width=w;

 

this.height=h; this.depth=d;

 

}

 

//default constructor box2(){

 

height=width=depth=2;

}

 

double fun_volume_box(){

 

return width*height*depth;

 

}

 

}

 

//the class “boxweight2” inherits the the properties of base class “BOX2” by the

//keyword extend

 

class boxweight2 extends box2{ double weight;

 

boxweight2(double w,double h,double d,double we){

 

//here super keyword is used to access the private members of base class super(w,h,d);

 

weight=we;

 

}

 

//default constructor boxweight2(){

 

//here super() is used to call the default constructor in the base class super();

 

weight=2;

}

 

}

 

public class superinherit {

 

public static void main(String args[]){

 

double volume;

 

boxweight2 mybox1=new boxweight2(10,10,10,10);

 

boxweight2 mybox2=new boxweight2();

 

volume=mybox1.fun_volume_box();

 

System.out.println("volume of mybox1 object is " + volume);

 

volume=mybox2.fun_volume_box(); System.out.println("Volume of mybox2 obj is " + volume);

}

 

}

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Web or internet Programming : JAVA : Java - Using super |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.