How to write override methods in Java

半腔热情 提交于 2021-02-11 15:54:54

问题


This is part of a homework assignment.

I am trying to make a class named RomanNumeral that has several methods. The first method, RomanNumeral checks whether a string rn is a Roman Numeral or not. The second method converts the Roman numeral into a decimal value. My problem lies with the rest of the methods. I am asked to create an override file for .equals(), .compareTo() and toString(). My question is how would I even begin doing this? What does it mean to override? Am I supposed to look at what they do, and emulate it? And if I am, where can look at the method that defines .compareTo() or toString()?

I can post my current code if it helps.


回答1:


Ok, from what I can see, you have 2 main questions here.

  1. What does it mean to override a method?
  2. How to I override a method?

Lets think up a new class, so that I can avoid doing your homework for you.

We have a class called Student, that stores 3 Strings.

  • First Name
  • Last Name
  • GPA

It might look something like this.

public class Student {
    String firstName;
    String lastName;
    String gpa

    public Student(String firstName, String lastName, String gpa){
        this.firstName = firstName;
        this.lastName = lastName;
        this.gpa = gpa;
    }

    // Perhaps some methods here

    public String getIdentity(){
        return this.lastName + ", " + this.firstName;
    }
}

You like the Student class, but you decide that it would be much better if you could keep track of a College studentId as well. One solution would be to extend the Student class.

By extending the class, we get access all of the methods (and constructors) that Student had, and we get to add some of our own. So lets call our new class CollegeStudent, and add a String for the studentId.

public class CollegeStudent extends Student{

    String studentId;

}

Now, with no additional work, I can create a CollegeStudent, and get it's identity.

// Code
CollegeStudent myCollegeStudent = new CollegeStudent("Dennis", "Ritchie", "2.2");
String identity = myCollegeStudent.getIdentity();
// Code

Ok, enough setup. Lets answer your questions.

So lets assume that instead of returning "Ritchie, Dennis", you would prefer getIdentity() to return the "studentId" for that college student. You could then override the getIdentity method.

By overriding the method, you will get to re-write getIdentity() so that it returns the studentId. The CollegeStudent class would look something like this.

public class CollegeStudent extends Student{

    String studentId;

    @Override
    public String getIdentity(){
        return this.studentId;
    }
}

To override a method, you must return the same type of object (String in our example), and you must accept the same parameters (our example did not accept any parameters)

You can also override constructors.

So how does this apply to your assignment? .equals(), .compareTo(), and .toString() are already defined because of the classes that you will be extending (such as Object). However you will want to re-define or override those methods so that they will be useful for your class. Perhaps your implementation of toString() will return the word "four" instead of "IV". Probably not, but the point is that you now have the freedom to decide how the method should be coded.

Hope this helps.




回答2:


When one class extends another, it inherits all of its non-private instance members.

For example, RomanNumeral extends Object, so it inherits the latter's toString() method. This means that you can call toString() on any RomanNumeral instance, and it will call the Object.toString() method.

However, RomanNumeral can choose to override this method by providing its own definition, that will supersede the one it inherited. Then, when you call toString() on a RomanNumeral instance, it will call the method that you defined. (This works even if you're referring to the RomanNumeral instance via an Object reference.)

So, you are being asked you to flesh out this rubric:

public class RomanNumeral {

    // ... your other methods ...

    @Override       // this line is optional
    public String toString() {
        // TODO define this method
    }

    @Override       // this line is optional
    public boolean equals(Object o) { // note: 'Object', *not* 'RomanNumeral'!
        // TODO define this method
    }

    @Override       // this line is optional
    public int hashCode() {
        // TODO define this method
    }

}

Note that, despite what you seem to have been told, there is no such thing as an "override file". The above methods are defined inside RomanNumeral.java, just like any other method.




回答3:


From the documentation:
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it overrides.

When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass.




回答4:


To override means to change the behaviour of instances by creating a new implementation of a method. Every Java class inherits equals(), hashCode() and toString() from the class Object.

Try to write new implementations of these methods in your class so toString() returns the RomanNumber as letters, equals() to return if the other object is als a RomanNumber and has the same value and respect the contract that two equal objects need to have the same hashcode.

Add an @Override annotation to your methods, to mark them as deliberate change and so let the compiler check the signature.




回答5:


What you need to do is redefine those methods:

public class RomanNumeral implements Comparable<RomanNumeral>{

@Override
public boolean equals(Object obj) {
// your conditions and return true or false
}

@Override
public String toString() {
return "Show the world my representation";
}

public int compareTo(T o) {
/* your conditions and if returns:
Less than zero -> instance precedes obj in the sort order.
Zero -> instance occurs in the same position in the sort order as obj
Greater than zero -> instance follows obj in the sort order)*/ 
}


来源:https://stackoverflow.com/questions/15349460/how-to-write-override-methods-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!