I had to do a Java program that said:
Write a program in java to implement Inheritance. Your program should have the following structure
- Create a Base class to hold two Integers and a method to Display them.
- In the derived Class add another Integer and Display it.
- Create a method in the same derived Class to add the three numbers.
- Pass the values to the integers and Display the results.
and I’m not that good at Java, so I don’t know if what I did was right or wrong or what! And I think I didn’t understand what was wanted quite well. Here is what I came up with:
public class firstclass {
int a=5;
int b=6;
public void Display (){
System.out.println(a+b);
}
}
public class secondclass extends firstclass {
int z=0;
public void Displaysecond (){
System.out.println(z);
}
public void add (){
z=a+b;
System.out.println(z);
}
}
public class mainOne {
public static void main(String[] args) {
firstclass call = new firstclass();
secondclass call2 = new secondclass();
call.Display();
call2.Displaysecond();
call2.add();
}
}
It runs without any problems but I get “11” for the “System.out.println(a+b);” while a = 5 and b = 6.
Am I going about this correctly?
You have a few problems. As Grammin mentioned, your add function is not what your teacher wanted. Your teacher wanted you to a, b, and z. So
Alternatively, you could make
void add()int add()and returnsum.Secondly, you are not following Java convention. Your variables need to be more inappropriately named, your classes need to start with uppercase and your methods need to start with lowercase.
Perhaps you should name your classes FirstClass, SecondClass, and MainClass?
Your methods: display(), displaySecond(), and add()
Your variables: a,b,c or num1, num2, num3. (for consistency)
Also, call.display() should yield the same result as call2.display() because SecondClass is a subclass of FirstClass. Read this for a better understanding of inheritance.
A side note: you should add your numbers in parentheses () for clarification and safety if you’re doing some sort of in-line math. For example
instead of