Tuesday, November 12, 2013

Using "super" keyword in example of inheritance

In below program we use method overriding, in method overriding if we haven;t use "super" keyword than you can not use it. In below program, we use "super" keyword in getdata and displaydata which we already used in first class and now when we inherit the second class than we are using method overriding that mean we using same method in second class, now to access the parent class member you can use "super" key word and we did same thing here. You can also use "super" keyword to call parent class constructor within child class constructor.


import java.io.*;

class empl{

int empno;
String name;
String position;
int ph;

void getdata()throws IOException
{

DataInputStream e = new DataInputStream(System.in);

System.out.println("Enter employee number: ");
empno = Integer.parseInt(e.readLine());

System.out.println("Enter your name: ");
name = e.readLine();

System.out.println("Enter the employee position: ");
position=e.readLine();

System.out.println("Enter the phone number: ");
ph = Integer.parseInt(e.readLine());

}



void displaydata() {

System.out.println(empno+"\t"+name+"\t"+position+"\t"+ph);

}

}

class manager extends empl{

int salary;
String secname;

void getdata() throws IOException{

super.getdata();

DataInputStream e= new DataInputStream(System.in);

System.out.println("Enter salary: ");
salary=Integer.parseInt(e.readLine());

System.out.println("Enter second name: ");
secname= e.readLine();

}

void displaydata(){
super.displaydata();
System.out.println(salary+"\t"+secname);
}
}
class inheritt{
public static void main(String []args) throws IOException{

manager e1= new manager();
manager e2= new manager();


e1.getdata();
e2.getdata();

e1.displaydata();
e2.displaydata();

}
}
____________________________________
Output:

Enter employee number:

Sunday, November 10, 2013

Use of "this" keyword with very simple example


class thiss{

int a,b;

thiss(){

a=1;
b=2;}

thiss(int c,int d){
this();
this.a=c;
this.b=d;

}

void displaydata(){

System.out.println("c= "+a);
System.out.println("d= "+b);
}

public static void main(String []arg){

thiss t1= new thiss();
t1.displaydata();

thiss t2= new thiss(3,4);
t2.displaydata();
}}

___________________
Output:

c= 1;
d=2;
c= 3;
d=4;