Overriding methods in java using super - java

So, I have to create 68 different summing methods using the datatypes, int, float, double and short. The class is called, OverloadingSums. Here is an example of one the methods.
public double sum(double x, float y, int z)
{
return x+y+z;
}
Now I'm being asked to create a class called ZeroSum, essentially copying OverloadingSum and returning everything to zero. Here is an example.
public double sum(double x, float y, int z)
{
return 0;
}
Then I'm being asked to create another class called RealSum, which will extend the ZeroSum class. I'm a little confused about the wording of this assignment, not sure if the stackoverflow community could help but I'm just extremly confused.
Here is the assignment requirements:
Now that we have thoroughly explored overloading we are going to
explore overriding. Create a class called ZeroSum.java. Take all of
the methods from OverloadingSum.java and change them to return all
zeros in ZeroSum.java. Next, create a class called RealSum.java. This
class, RealSum, will extend the ZeroSum class. Having all zeros for
our sums isn't very useful. We will need to override the parent, or
super class methods to produce real results. Create the necessary
methods to override all of those in the ZeroSum.java. When you are
done run your classes against DrivingSum.java.
This is what I have in my main method:
public class DrivingSum {
public static void main(String[] args) {
int x = 10;
int y = 20;
// x + y = 30....yay?
ZeroSum zero= new ZeroSum();
RealSum real= new RealSum();
System.out.println("Calling ZeroSum " + zero.sum(x,y) );
System.out.println("Calling ZeroSum " + real.sum(x,y) );
}
}
So, from how I'm understanding this I wrote the following code:
public class ZeroSum extends RealSum{
public double sum(double x, float y, int z)
{
return super.sum(x,y,z);
}
This will grab the method from RealSum, instead of using the sum method located in the ZeroSum class. So when I run the main method, zero.sum(x,y) gives me 30.
The confusion comes from the fact that the assignment asks me to set everything in ZeroSum returning to zero. If I extend ZeroSum to RealSum, it doesn't really make a difference. Am I doing this correctly? or Am I just overthinking this way too much?

The goal of this assignment is to explore overriding concept, where function executed depends on type of object it called upon on run time, so you will have something like this :
public class ZeroSum {
public double sum(double x, float y)
{
return 0;
}
}
public class RealSum extends ZeroSum{
public double sum(double x, float y)
{
return x+y;
}
}
public class DrivingSum {
public static void main(String[] args) {
int x = 10;
int y = 20;
// x + y = 30....yay?
ZeroSum zero= new ZeroSum();
ZeroSum real= new RealSum();
System.out.println("Calling ZeroSum " + zero.sum(x,y) ); //here the sum will return zero
System.out.println("Calling ZeroSum " + real.sum(x,y) ); //here the sum will return 30
}

I believe he's trying to make a point in which whatever you write in the parent class is transferred (this is called inheritage) to the child. You can override this by writing a method in the child class using the same name and arguments as the parent class' method.
I also believe you read the assignment a bit wrong, it said:
This class, RealSum, will extend the ZeroSum class.
I interpret this as RealSum is the child to ZeroSum, not the other way around as such:
public class RealSum extends ZeroSum{
//code code code
}
This means everything in ZeroSum is set to 0 and RealSum set new values, not using the super. I'm not betting my hand this is correct but try to read the assignment again after a break and some fresh air :)
Hope this helps!

Related

Convert double to string and return it to main

A part of my homework is to convert three double variables to one String and print it from the main method. I have created a separate class where I try to create the string. When I try to print the string from the main method, i dont understand how to do it.
Main-class
public static void main(String[] args) {
System.out.println(Point.toString());
}
Point
public class Point {
public String toString(Double xVal, Double yVal, Double zVal){
String p= Double.toString(this.xVal) + ":" + Double.toString(this.yVal) +
":" + Double.toString(this.zVal);
return p;
}
}
This is just a part of my code, can someone help me with the part where i try to print the string?
It seems that you tried to create some sort of utility class, so...
First you need to make the method which prints the values in Point class static, so you don't need to create instances of Point in order to call it.
Second, I highly recommend to change the method name in class Point because there is a toString method already inherited from Object. This may lead to confusions since the goal of the inherited method is not the same the one you created this toString method for.
Also, be careful inside the method to use the values received as parameter and not the (missing) instance attributes. That is, use values xVal, yVal and zVal, not this.xVal, this.yVal and this.zVal.
So, this would go kind of this way:
public class Point {
// changed from `toString` to `convertToString`, use the name which fits better your needs, except `toString`
public static String convertToString(Double xVal, Double yVal, Double zVal) {
// use `xVal`, not `this.xVal` and the same for the other variables
String p = Double.toString(xVal) + ":" + Double.toString(yVal) + ":" + Double.toString(zVal);
return p;
}
}
Then in your main class:
public class Main {
public static void main(String[] args) {
System.out.println(Point.convertToString(1d, 2d, 3d)); // you can replace this sample values with the real ones
}
}
Of course, there are many ways to do this, but the "proper" way, using toString would be to make the x, y and z values attributes of the class (and, optionally, a constructor and getters and setters for those attributes), and have toString print the values of those attributes of the current instance.
public class Point {
Double xVal, yVal, zVal;
public Point(Double x, Double y, Double z) {
this.xVal = x;
this.yVal = y;
this.zVal = z;
}
public String toString() {
return String.format("%s:%s:%s", this.xVal, this.yVal, this.zVal);
}
}
Here, String.format("%s:%s:%s", ...) is a nicer way to format the string with the three numbers, but you can just as well keep yours. The nth %s will automatically convert the parameter in that position to string and insert it at that position. You could also use e.g. %.2f for specific floating -point format with more options.
You can create a new instance of the Point class with the given coordinates and print it. Here, you do not have to explicitly call toString, as it will be automatically called when println tries to convert its argument to a string.
public static void main(String[] args) {
Point p = new Point(1.1, 2.2, 3.3);
System.out.println(p);
}
You need to create object of the class Point then invoke the method toString with the three double value as arguments, like you defined inside Point class.
public static void main(String[] args) {
Point p = new Point();
System.out.println(p.toString(2.0,3.5,4.6));
}
I think the correct way is to create a new point with its parameters and override the toString method inherited:
public class Point{
Double xVal; Double yVal; Double zVal;
void Point(Double xVal, Double yVal, Double zVal)
{
this.xVal = xVal;
this.yVal = yVal;
this.zVal = zVal;
}
#Override
public String toString(){
String p= Double.toString(this.xVal) + ":" + Double.toString(this.yVal) +
":" + Double.toString(this.zVal);
return p;
}
}
So the main:
public static void main(String[] args) {
Point p = new Point(1.3,2.0,.30);
System.out.println(p.toString());
}

having trouble with ternary operators

I was wandering how to make custom classes that can be used through out all of java eclipse. For example if you make any basic program you can call pre determined classes, like you can just type Math.abs(x); instead of having to go out of your way and typing
if (x<0) x = x * -1;
else x = x;
I would like to design my own custom classes for basic functions that I use a lot that i can use I in any program regardless of if they are in the same project or not.
custom classes that can be used through out all of java eclipse...
you can do that with any class as soon as you import that and define the right visibility for its data....
class MyRandom{
public static int MultiplybyTwo(int number){
return number * 2;
}
public static int DividebyTwo(int number){
return number / 2;
}
}
import MyRandom;
class Test{
public static void main(string[] args){
int x = MyRandom.MultiplyByThow(9);
System.out.println("the result is: " + x);
}
}
on the other hand, this makes no sense:
else x=x;

What is the difference between void and return even though I can get same output on both?

i made a small program for summing two numbers
if i used a void type method it will be like this
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
getSum(x,y);
}
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
} }
here if i used a method that returns a value i will get same output!
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
int r = getSum(x,y);
System.out.println("sum = " + r);
}
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}}
so i'm confused what is the benefit of returning a value if i can finish my program with a void type method?
The point is not to get the result but the way we get the result
consider
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
}
will print the output to the screen after calculation
but when we use return
as you have done it later
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}
this function will respond back the sum. that sum can be stored in a variable
can be used afterwards
like in recursion
In small programs, you won't get the difference but while writing the big programs you have to make several functions which are being called several times and you may need the output of one function into other.
In that case, you will require return so that the output of one function can be used into other.
Hope this helps!!
I think the answer is that, if you're calling getSum() method with a return type in any other class.. you would get a returned value which can be used for further processing. .
Where as in void that's not possible... Hope this helps... Reply if any doubts..
I can understand why you have this question.
First of all, you should know that in real development, we do not use console logs.
System.out.Println();
This is used only for debugging and that too in very rare cases.
The whole point of a function is to take some input and convert to something else.
So,
public static int getSum(int x, int y) {
return x+y;
}
public static void main(String[] args) {
System.out.Println(getSum(5,10));
}
This is the better solution.
Best Regards,
Rakesh
When you use the keyword void it means that method doesn't return anything at all. If you declare a return type different to void at the method statement instead, that method must return obligatorily a valid value to the declared return type using the keyword return followed by a variable/value to send back to the class that called the method.
Defining methods here you have the java documentation for a method declaration
Answering your question, in small programs that work with primitive values it doesn't really matter but in complex program when you usually need to return specifics object types, i.e an ArrayList or actually an instance of a class you created you can't simply put it into a System.out.println and send it to the console, mostly you'll want to get something from a method and that something usually can be a more complex object than an integer or a string, the way to get that something is through the return type defined by the method's statement.
A common use of return types is when your method is static and it can't interact with the non-static instance variables of the class, this type of static methods usually get values from their arguments, do a certain kind of progress and then return a result that the method's caller can use.
Returning a value enables you to use that value in whichever way you want, including printing it or assigning it to variable for further processing. If on the other hand you print the value in the method and not return anything, i.e. making the method of type void, then that's all you can do with that method.

Call a method from another class(not main class)

How to call distanceTo(Point p) of Point.java into Point2.java under a method takes no parameter? There should be a way but I cannot find from my materials. Could anybody help me? It has been doing 2 days. Please help...
---------------------Point.java---------------------------------
public class Point{
private int x;
private int y;
//x and y coordinates as parameters
public Point(int x, int y){
this.x = x;
this.y = y;
}
//I want to call this method by calling a method which taken no parameter in Point2.java.
public double distanceTo(Point p){
return Math.sqrt(((x - p.x) * (x - p.x)) + ((y - p.y) * (y - p.y)));
}
}
---------------------ClonePoint.java---------------------------------
public class ClonePoint{
private int a;
private int b;
//x and y coordinates as parameters
public ClonePoint(int a, int b){
this.a = a;
this.b = b;
}
//I failed with this way. Can anybody correct me?
public double measureDistance(){//it should be takes no parameter.
return distanceTo(ClonePoint p)
}
}
----------------------PointDriver.java-----------------------------
public class PointDriver {
public static void main(String [] args) {
Point2 nn = new Point2(11, 22);
Point2 mm = new Point2(33, 44);
System.out.println(nn.distanceTo(mm)); //I succeeded with this!
System.out.println(nn.measureDistance(mm)); //But I got an error illegal start of expression
}
}
#Evan a class is a generalized container for your things. A car, a person, a point (in your case).
Everytime you want to "create" one or more object of your defined class, you instantiate them:
Person evan = new Person();
Person rob = new Person();
both of us are person, you don't really need to define class Person1 and Person2!
And in a class you should define the methods used to "relate" to other similar objects.
For example:
// In Person.java
public void greet(Person p) {
System.out.println("My name is "+this.name+". Nice to meet you +"p.getName());
}
// In main
rob.greet(evan); // it now gives compile errors of course but take the point :P
What you want to achieve is to create a better and more complete Point class with all the methods you want to use. In the end, just initialize more Point objects (same class!) in your main and play with them.
Hope it helps :)
EDIT
Ok, perhaps I've got what your homework wants you to perform.
A "parameter-less" method measureDistance() should make you wonder one important thing: "distance FROM which point????".
Obviously, if the function takes no parameters all the information needed to that calculus must be in the object which calls it. Don't you think?
So, you probably want to achieve a secondary class (if you really need to define it as Point2 it's ok, but change that name because it's confusing) which can take a Point in its constructor (saving this information in itself) and then use that Point to measure distance from it.
Example
public class Point2{
private int a;
private int b;
private Point startingPoint;
public Point2(int a, int b, Point p){
this.a = a;
this.b = b;
startingPoint = p;
}
// Computes the distance from starting point to this
public double measureDistance(){//it takes no parameter.
return startingPoint.distanceTo(a, b);
}
/*
if you can't edit distanceTo() it gets a little verbose but you must create a
Point with Point2 coordinates - remember this example when you will study Inheritance
public double measureDistance() {
Point endingPoint = new Point(a, b);
return startingPoint.distanceTo(endingPoint);
}
*/
}
First, it is not good idea to duplicate a class that does the same thing because you are doing extra unneeded work. Second, if you make various point types, you are loosing the advantage of seamless compatibility between them.
Then, if you want to call method from other class you can do it like this:
NameOfOtherClass.SomeMethod()
But you have to declare the SomeMethod in the other class as static...
public static double SomeMethod() { ... };
But then you can't use the method to access the data of your concrete points you have created in your code, so any data should be put into parameters.
If you want to do it your way, you have to just add a parameter to public double measureDistance()
function so the function has access to another point to measure distance to.

inheritance class fraction/integer

So, I created a simple class named Test, as follows:
import prog.utili.IntegerB;
//It's a custom class
class Test
{
public static void main(String[] args)
{
IntegerB a = new IntegerB(1);
IntegerB b = new IntegerB(2);
IntegerB sum = a.plus(b);
System.out.println(sum);
}
}
I wanted to practise with inheritance so I created two custom classes. Fraction...
package prog.utili;
public class Fraction
{
private int num;
private int den;
public Fraction(int x, int y)
{
[...]
}
public Fraction(int x)
{
this(x, 1);
}
public Fraction plus(Fraction f)
{
int n = this.num * f.den + this.den * f.num;
int d = this.den * f.den;
return new Fraction(n, d);
}
[...]
}
...and IntegerB:
package prog.utili;
public class IntegerB extends Fraction
{
public IntegerB(int num)
{
super(num);
}
public IntegerB plus(IntegerB other)
{
return (IntegerB)this.plus(other);
}
}
The problem is I keep getting the same error:
at prog.utili.IntegerB.plus(IntegerB.java:11)
I know I could simply solve the problem by just deleting the last method on IntegerB and replacing the 9th line of Test.java with
IntegerB sum = (IntegerB)a.plus(b)
but I absolutely want to do it using the inheritance rules over the "plus" method!
To implement the method plus(IntegerB), you call plus(IntegerB), which calls plus(IntegerB), etc. etc. until you get a StackOverflowError.
Provide an actual implementation for your method:
return new IntegerB(this.getNum() + other.getNum());
or
return new IntegerB(super.plus(other).getNum());
Also note that replacing the last line of Test.java by
IntegerB sum = (IntegerB)a.plus(b);
wouldn't work, since the plus() method in Fraction doesn't return an IntegerB, but a Fraction. You would thus get a ClassCastException.
The problem here is that IntegerB.plus does not override Fraction.plus, it overloads it. This is because the argument types are different. Thus when IntegerB.plus calls this.plus(other), it ends up calling itself, which then calls itself, which then calls itself until you get a StackOverflow (thus sending you to stackoverflow : )).
It seems like you want to call plus(Fraction) instead of plus(IntegerB). To do that, you can explicitly upcast other:
return plus((Fraction) other);
This cast has no effect other than to tell the compiler that you want to call the version of plus that handles Fractions, even though you know you have an IntegerB.
However, this method would not return an IntegerB, but just a Fraction whose denominator is 1. You could conceivably override plus to return an IntegerB if the denominator of the result is 1, but that might lead to unexpected situations where a.plus(b) is not equal to b.plus(a) because one is a Fraction while the other is an IntegerB. Alternatively, you could return IntegerB objects from Fraction.plus when possible.

Categories