super keyword in Java

super keyword is used to refer to the inherited class’s elements.

[java title=”SuperMethod.java” gutter=”true” highlight=”5″]
public class SuperMethod {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

// Initializing Zebra class with default constructor
zebra z1 = new zebra ();
System.out.println ( "Zebra is " + z1.name + " of type " + z1.type +
" with " + z1.number_of_legs + " legs"
+ " and I am " + z1.striped);

// Initializing Zebra class with the number_of_legs constructor
zebra z2 = new zebra (4);

System.out.println ( "Zebra is " + z2.name + " of type " + z2.type +
" with " + z2.number_of_legs + " legs"
+ "and I am " + z2.striped);

// Initializing Zebra class with zebra (String name, String type, int number_of_legs) constructor
// This will tell you if the default super constructor is called or NOT in case a over-ridden
// super constructor is called
zebra z3 = new zebra( "ZEBRA", "HERBIVORE" , 4);
System.out.println ( "Zebra is " + z3.name + " of type " + z3.type +
" with " + z3.number_of_legs + " legs"
+ "and I am " + z3.striped);

}

}

class animals
{
public String name ;
public String type ;
public String striped;

animals ()
{
this.name = "Any animal";
this.type = "Herbivore/Carnivore";
this.striped = "YES/NO";
}

animals (String name , String type)
{
this.name = name;
this.type = type;
}
}

class zebra extends animals

{
int number_of_legs;

zebra()
{
// super constructor is called here by default
System.out.println ( "Zebra initialized ");
}

zebra (int number_of_legs)
{
// super constructor is called by default here as well
this.number_of_legs = number_of_legs;
}

zebra (String name, String type, int number_of_legs)
{
// default super constructor is over-ridden here
super(name,type);
this.number_of_legs = number_of_legs;

}

}

[/java]

asdf

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s