B.java

Advanced Concepts Used: Inheritance and Function Overriding
Observation: It has been observed that when the function add in A was overridden by class B then calling the function directly from Excercise class runs the original function.


Excercise.java
This code develops two objects one for class A and another object class B.

<strong></strong>package com.gl;
public class Exercise {
public static void main(String args [])
{
B x= new B();
x.run();
A xx= new A();
xx.a=10;
xx.b=20;
System.out.println(xx.add());
System.out.println(x.add());


}



}


<strong>A.java
</strong>Just defines four basic mathematical operation.

<strong></strong>
package com.gl;

public class A {

int a,b;
int add()
{
return a+b;
}
int sub()
{
return a-b;
}
int mul()
{
return a*b;
}


}


B.java
This class inherits function of class A and then does function overriding.

package com.gl;
//inheritance
public class B extends A {

//function overriding
int add()
{
return a-b;
}
void run()
{
a=5;
b=10;
System.out.println(add());
}

}
Advertisements

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

%d bloggers like this: