Can someone show me a simple program that will display how to extend and use super?

Hi ceyesuma,

The super method is used to call a parent class's constructor method in the child class's constructor method. As an example...

public class Shape {
int height;
int width;
public Shape() {
height = 1;
width = 2;
}
}

public class Triangle extends Shape {
double area;
public Triangle() {
super(); // this means height = 1 and width = 2
area = height * width / 2.0;
}
}

In this example, Circle is the child class of Shape and it's constructor calls super as its first instruction and then extends it by doing something after.

Hope this helps,
darkagn

Hi ceyesuma,

The super method is used to call a parent class's constructor method in the child class's constructor method. As an example...

public class Shape {
int height;
int width;
public Shape() {
height = 1;
width = 2;
}
}

public class Triangle extends Shape {
double area;
public Triangle() {
super(); // this means height = 1 and width = 2
area = height * width / 2.0;
}
}

In this example, Circle is the child class of Shape and it's constructor calls super as its first instruction and then extends it by doing something after.

Hope this helps,
darkagn

Thanks darkagn It's a start.

Super can also be used to call a parent class method that you overriding to extend the original functionality. i.e.

public void someMethod(){
  // go ahead and do what parent class has defined
  super.someMethod();

  // now do a few other things that this subclass needs...
}

So any child class of Super is going to begin with a height of 1 and width of 2.
You could then add things such as area, volume and other attributes from that base.

Could you also change one of the original attributes? Say if I wanted to call Super, but make the newest object have a height of 2.

So any child class of Super is going to begin with a height of 1 and width of 2.
You could then add things such as area, volume and other attributes from that base.

Could you also change one of the original attributes? Say if I wanted to call Super, but make the newest object have a height of 2.

Yes, you can change the base class variables as long as their scope allows. With no scope modifier, the variable is package-protected, which means other classes in the same package can access it. Protected access will allow classes in the same package and also any subclasses to access it. Public allows anything to access it. If you declare it private though, not even the subclasses can access the variable.

commented: always helpful +1

great! thanks. I will try to use this and see if I undestand.

Thanks Ezzaral, that is exactly what I needed to know.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.