cancel
Showing results for 
Search instead for 
Did you mean: 

Overriding methods

Former Member
0 Kudos

I am having some compilation errors with the following code,whats wrong with this code, could you help me please

Thanks. I am trying to access the method in the Base class, using the verb super, but I am getting an error message "Non-Static variable super cannot be referenced from a static context"

class Math {

int Add(int a, int b) {

return a + b;

}

public int Sub(int a, int b) {

return (a + b);

}}

class BigMath extends Math {

int Multi(int a, int b) {

return a * b;}

public int Sub(int a, int b) {

return (a - b);}

}

class inherit {

public static void main(String args[]) {

int ans1;

int ans2;

int ans3;

BigMath boy1 = new BigMath();

ans1 = boy1.Add( 10, 5);

System.out.println("The sum is : " + ans1);

ans2 = super.Sub( 10, 5);

System.out.println("The difference is " + ans2);

ans3 = boy1.Multi( 5, 5);

System.out.println("The Multiplication is : " + ans3);

}

}

Accepted Solutions (0)

Answers (2)

Answers (2)

Former Member
0 Kudos

Can some one provide me a simple example for the Overriding Methods Please?

Former Member
0 Kudos

Hi

This should works.

public class OverRidden {

public static void main(String args[]) {

Circle c = new Circle(12.10);

Cylinder cyl = new Cylinder(12.12,10);

Circle ci;

ci=c;

System.out.println("Area"+ci.getArea());

ci=cyl;

System.out.println("Area"+ci.getArea());

}

}

class Circle {

protected double radius;

public Circle(double radius) {

this.radius = radius;

}

public double getArea() {

return Math.PIradiusradius;

}

}

class Cylinder extends Circle {

protected double length;

public Cylinder(double radius, double length) {

super(radius);

this.length = length;

}

public double getArea() {

return 2super.getArea()+2Math.PIradiuslength;

}

}

Thanks

Lohi.

Former Member
0 Kudos

Thanks Lohitha.

You have defined two objects from the Base class and subclass respectively and it WORK FINE,

Circle c = new Circle(12.10);

Cylinder cyl = new Cylinder(12.12,10);

I want to define only one object from the Subclass and from that object i want to access the Base class Method.

How to do that?

Thanks

Former Member
0 Kudos

Hi,

Try this code.

public class two {

public static void main(String args[]) {

int ans1;

int ans2;

int ans3;

BigMath boy1 = new BigMath();

ans1 = boy1.Add( 10,10);

System.out.println("The sum is : " + ans1);

ans2 = boy1.Sub( 10, 5);

System.out.println("The difference is " + ans2);

ans3 = boy1.Multi( 5, 5);

System.out.println("The Multiplication is : " + ans3);

}

}

class Math {

int Add(int a,int b) {

return a + b;

}

public int Sub(int a, int b) {

return (a + b);

}

}

class BigMath extends Math {

int Multi(int a, int b) {

return a * b;

}

}

it might help your requirement.

<b> is this OK or looking any thing else </b>

Thanks,

Lohi

Message was edited by: Lohitha M

Former Member
0 Kudos