Help me to correct my logic error..

import java.util.*;

abstract class Arithmetic

{
int a,b;

abstract void calc(); 

}

class Add extends Arithmetic

{
void calc()

{ 
 	System.out.println("The sum is " + (a+b)); 
} 

}
class Sub extends Arithmetic

{
void calc()

{ 
 	System.out.println("The difference is " + (a-b)); 
} 

}

class Abst
{
public static void main (String args[])

{ 
	System.out.println("Enter any Two numbers : "); 

	Scanner sc = new Scanner(System.in); 
	int a = sc.nextInt();  	 	
	int b = sc.nextInt();

 	Add obj1 = new Add();    	 	
	 	obj1.calc();    	 	
	Sub obj2 = new Sub();    	 	
	obj2.calc();  
} 

}

C:\Users\User>java Abst

Enter any Two numbers :

3

2

The sum is 0

The difference is 0

//output when execute it

The variables a and b that are used for the computations, are the class members of obj1 or obj2. The problem is, that you never initialize those values, so Java initializes them with 0. The variables a and b that you initialize in the main method are not the same variables. They are local variables.

Easy solution would be to initialize the values with:

Add obj1 = new Add();           
obj1.a = a;
obj1.b = b;
obj1.calc();

Or write/use constructors.

1 Like