Rnosmodule java 31 error method does not override or implement a method from a supertype

I have looked all around but can't figure out why I'm getting the error error: method does not override or implement a method from a supertype This highlights the two @Overrides I have in a me...

I have looked all around but can’t figure out why I’m getting the error

error: method does not override or implement a method from a supertype

This highlights the two @Overrides I have in a method (subroutine?). Here’s my MainActivity.java — the part of the code it occurs in the queryBooks() method at the end — the @Overrides are both underlined red.

package com.example.batman.myapplication;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.view.MenuItemCompat;
//import android.support.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    TextView mainTextView;
    EditText mainEditText;
    ListView mainListView;
    ArrayAdapter mArrayAdapter;
//  ArrayList<String> mNameList = new ArrayList<String>();
    ArrayList mNameList = new ArrayList();
    android.support.v7.widget.ShareActionProvider mShareActionProvider;

    // This is for internet stuff
    private static final String QUERY_URL = "http://openlibrary.org/search.json?q=";


    // Setting up the storage of data
    private static final String PREFS = "prefs";
    private static final String PREF_NAME = "name";
    SharedPreferences mSharedPreferences;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 1. Access the TextView defined in layout XML
        // and then set its text
        mainTextView = (TextView) findViewById(R.id.main_textview);
//      mainTextView.setText("Set in Java!");

        Button mainButton;
        mainButton = (Button) findViewById(R.id.main_button);
        mainButton.setOnClickListener(this);

        // 3.  Access the EditText defined in layout XML
        mainEditText = (EditText) findViewById(R.id.main_edittext);

        // 4. Access the ListView
        mainListView = (ListView) findViewById(R.id.main_listview);
        // Create an ArrayAdapter for the ListView
        mArrayAdapter = new ArrayAdapter(this,
                android.R.layout.simple_list_item_1,
                mNameList);
        // Set the ListView to use the ArrayAdapter
        mainListView.setAdapter(mArrayAdapter);

        // 5. Set this activity to react to list items being pressed
        mainListView.setOnItemClickListener(this);

        // 7. Greet the user, or ask for their name if new
        displayWelcome();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu.
        // Adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        // Access the Share Item defined in menu XML
        MenuItem shareItem = menu.findItem(R.id.menu_item_share);

        // Access the object responsible for
        // putting together the sharing submenu
        if (shareItem != null) {
            mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
        }

        // Create an Intent to share your content
        setShareIntent();

        return true;
    }

    private void setShareIntent() {

        if (mShareActionProvider != null) {

            // create an Intent with the contents of the TextView
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Android Development");
            shareIntent.putExtra(Intent.EXTRA_TEXT, mainTextView.getText());

            // Make sure the provider knows
            // it should work with that Intent
            mShareActionProvider.setShareIntent(shareIntent);
        }
    }

    @Override
    public void onClick(View v) {
//      // Take what was typed into the EditText
//      // and use in TextView
//      mainTextView.setText(mainEditText.getText().toString() + ".");
//
//      // Also add that value to the list shown in the ListView
//      mNameList.add(mainEditText.getText().toString());
//      mArrayAdapter.notifyDataSetChanged();
//      // 6. The text you'd like to share has changed,
//      // and you need to update
//      setShareIntent();
//
//      if(v == mainEditText) {
//          mainEditText.setText("");
//      }

        // 9. Take what was typed into the EditText and use in search
        // (the above is commented out, per tutorial part 3 - this takes its place as input
        queryBooks(mainEditText.getText().toString());
//      mainEditText.setText("");
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        // Log the item's position and contents
        // to the console in Debug
        Log.d("My Application", position + ": " + mNameList.get(position));
    }

    public void displayWelcome() {

        // Access the device's key-value storage
        mSharedPreferences = getSharedPreferences(PREFS, MODE_PRIVATE);

        // Read the user's name,
        // or an empty string if nothing found
        String name = mSharedPreferences.getString(PREF_NAME, "");

        if (name.length() > 0) {

            // If the name is valid, display a Toast welcoming them
            Toast.makeText(this, "Welcome back, " + name + "!", Toast.LENGTH_LONG).show();
        } else {

            // otherwise, show a dialog to ask for their name
            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("Hello!");
            alert.setMessage("What is your name?");

            // Create EditText for entry
            final EditText input = new EditText(this);
            alert.setView(input);

            // Make an "OK" button to save the name
            alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int whichButton) {

                    // Grab the EditText's input
                    String inputName = input.getText().toString();

                    // Put it into memory (don't forget to commit!)
                    SharedPreferences.Editor e = mSharedPreferences.edit();
                    e.putString(PREF_NAME, inputName);
                    e.commit();

                    // Welcome the new user
                    Toast.makeText(getApplicationContext(), "Welcome, " + inputName + "!", Toast.LENGTH_LONG).show();
                }
            });
        // Make a "Cancel" button
        // that simply dismisses the alert
                    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {}
                    });

            alert.show();
    }
    }

    // Internet stuff
    private void queryBooks(String searchString) {

        // Prepare your search string to be put in a URL
        // It might have reserved characters or something
        String urlString = "";
        try {
            urlString = URLEncoder.encode(searchString, "UTF-8");
        } catch (UnsupportedEncodingException e) {

            // if this fails for some reason, let the user know why
            e.printStackTrace();
            Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }

        // Create a client to perform networking
        AsyncHttpClient client = new AsyncHttpClient();

        // Have the client get a JSONArray of data
        // and define how to respond
        client.get(QUERY_URL + urlString,
                new JsonHttpResponseHandler() {

                    @Override // THIS METHOD DOES NOT OVERRIDE METHOD FROM ITS SUPERCLASS ??
                    public void onSuccess(JSONObject jsonObject) {
                        // Display a "Toast" message
                        // to announce your success
                        Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_LONG).show();

                        // 8. For now, just log results
                        Log.d("omg android", jsonObject.toString());
                    }

                    @Override // THIS METHOD DOES NOT OVERRIDE METHOD FROM ITS SUPERCLASS ??
                    public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
                        // Display a "Toast" message
                        // to announce the failure
                        Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " + throwable.getMessage(), Toast.LENGTH_LONG).show();

                        // Log error message
                        // to help solve any problems
                        Log.e("omg android", statusCode + " " + throwable.getMessage());
                    }
                });
    }
} // end class

(For what it’s worth, I’m following this tutorial).

Thanks for any thoughts!

Я получаю ошибку method does not override or implement a method from a supertype @Override. Я хочу напечатать «не может изменить мощность автомобиля» после того, как он напечатает одну машину. Мне нужно переопределить setCapacity, чтобы напечатать эту другую часть. Я считаю, что код в основном правильный, но не уверен, почему он не корректно переопределяет метод setCapacity. Окончательный результат:

New capacity = 1600
Vehicle Info:
capacity = 1600cc
make = Mazda
Cannot change capacity of a car
Vehicle Info:
capacity = 1200cc
make = Holden
type = sedan
model = Barina

Мой код:

class Vehicle {  // base class

   public void setCapacity(int setCapacity) {
     this.capacity = setCapacity;
      System.out.println("New Capacity = " + setCapacity);
   }

   int capacity;
   String make;

   Vehicle(int theCapacity, String theMake) {
      capacity = theCapacity;
      make = theMake;
   }

   void print() {
      System.out.println("Vehicle Info:");
      System.out.println("  capacity = " + capacity + "cc" );
      System.out.println("  make = " + make );
   }
}

class Car extends Vehicle {
   public String type;
   public String model;

   public Car(int theCapacity, String theMake, String theType, String theModel) {
      super(theCapacity, theMake);
      type = theType;
      model = theModel;
   }

   @Override
   public void print() {
      super.print();
      System.out.println("  type = " + type);
      System.out.println("  model = " + model);

   }

     @Override
     public void setCapacity() {
       super.print();
       System.out.println("Cannot change capacity of a car");
     }       
 }

class Task3 {

   public static void main (String[]args){
      Car car1 = new Car (1200,"Holden","sedan","Barina" );
      Vehicle v1 = new Vehicle (1500,"Mazda");
      v1.setCapacity(1600);
      v1.print();
      car1.setCapacity(1600);
      car1.print();
   }
}

3 ответа

Лучший ответ

Сигнатура createCapacity отличается в классах Vehicle и Car. Итак, есть ошибка компиляции. В классе Vehicle у вас есть аргумент setCapacity, но в классе Car список аргументов метода пуст. Таким образом, переопределение невозможно.

@Override
public void setCapacity(   int capacity   ) { --> **adding this argument here will fix the issue.**
    super.print();
    System.out.println("Cannot change capacity of a car");
}

public void setCapacity(int setCapacity) {
    this.capacity = setCapacity;
    System.out.println("New Capacity = " + setCapacity);
}


0

Ankur Chrungoo
17 Окт 2018 в 14:16

Существует несоответствие в сигнатуре метода child и parent для setCapacity(). Если вы хотите переопределить метод из родительского класса в дочернем классе, тогда он должен иметь такую же сигнатуру.

+ Изменить

public void setCapacity() { //... }

К

public void setCapacity(int setCapacity) { // ... }

В классе Car.

В вашем коде вы пропустили параметр setCapacity, и поэтому компилятор жалуется.


1

Nicholas K
17 Окт 2018 в 13:07

void setCapacity(int setCapacity) не переопределяется. void setCapacity() и void setCapacity(int setCapacity) — два разных метода. Поэтому генерирует аннотацию @Override ошибки компиляции.

Что касается терминологии, в этом сценарии setCapacity считается перегруженным.


0

Michal
17 Окт 2018 в 13:09

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

kemishobowale

Hello
I’m getting this message but i’m not sure as to why, please help?

error: method does not override or implement a method from a supertype @Override

package com.teamtreehouse;
import java.util.Date;
import java.lang.Object;

public class Treet {
//m to show its the member (or class?) variable
private String mAuthor;
private String mDescription;
private Date mCreationDate;

public Treet(String Author, String Description, Date CreationDate){
this.mAuthor = Author;
this.mDescription = Description;
this.mCreationDate = CreationDate;
}

public String getAuthor(){
return mAuthor;
}

@Override
public String toString(){
return String.format(«Treet: «%s» by %s on %s», mDescription, mAuthor, mCreationDate);
}

@Override
public int compareTo(Object obj){
Treet other = (Treet) obj; //cast to treet
if (equals(other)){ //treet compared to treet is 0
return 0;
}
int dateCmp = mCreationDate.compareTo(other.mCreationDate); //compare the dates of
//the treet if it is equal (0) run a check on descritption to make sure the treet
//are not identical
if(dateCmp == 0){
return mDescription.compareTo(other.mDescription);
}
return dateCmp;
}

public String getDescription(){
return mDescription;
}

public Date getCreationDate(){
return mCreationDate;
}

public String[] getWords(){
return mDescription.toLowerCase().split(«[^w]+»);
}
}

3 Answers

Wout Ceulemans

Nicolás Lavín

Chufan Xiao

метод не переопределяет или не реализует метод из ошибки супертипа

Вопрос:

Я пытаюсь создать механизм отмены/повтора для своей шахматной игры. Я решил использовать структуру данных стека, которая будет построена на ArrayList. Я также хочу, чтобы мои классы UndoStack и RedoStack были одиночными. Однако я Получать

method does not override or implement a method from a supertype

pop() in UndoStack cannot implement pop() in IStackable
return type Move is not compatible with cgas5.Move
where Move is a type-variable:
Move extends Object declared in class UndoStack

ошибка..

Вот мой интерфейс IStackable:

package cgas5;


public interface IStackable {

abstract public Move pop();

abstract public void push(Move m);

}

и мой класс UndoStack

package cgas5;

import java.util.ArrayList;

public class UndoStack<Move> extends ArrayList<Move> implements IStackable {

UndoStack undoStack;

private UndoStack() {
undoStack = new UndoStack();
}

public UndoStack getUndoStack() {
if (undoStack == null) {
undoStack = new UndoStack();
}
return undoStack;
}

@Override
public Move pop() {
Move m = get(size() - 1);
remove(size() - 1);
return m;

}

@Override
public void push(Move m) {
add(m);
}
}

и если это необходимо, мой класс Move:

package cgas5;

public class Move {
private Piece pieceToMove;
private Square currentSquare;
private Square targetSquare;
private Piece capturedPiece;
private Piece promotedPiece;

public Move(){

}

public Move(Piece pieceToMove, Square currentSquare, Square targetSquare){
this.pieceToMove = pieceToMove;
this.currentSquare = currentSquare;
this.targetSquare = targetSquare;
}

public Piece getPieceToMove() {
return pieceToMove;
}

public void setPieceToMove(Piece pieceToMove) {
this.pieceToMove = pieceToMove;
}

public Square getCurrentSquare() {
return currentSquare;
}

public void setCurrentSquare(Square currentSquare) {
this.currentSquare = currentSquare;
}

public Square getTargetSquare() {
return targetSquare;
}

public void setTargetSquare(Square targetSquare) {
this.targetSquare = targetSquare;
}

public Piece getCapturedPiece() {
return capturedPiece;
}

public void setCapturedPiece(Piece capturedPiece) {
this.capturedPiece = capturedPiece;
}

public Piece getPromotedPiece() {
return promotedPiece;
}

public void setPromotedPiece(Piece promotedPiece) {
this.promotedPiece = promotedPiece;
}

}

Заранее спасибо..

Лучший ответ:

Это проблема:

public class UndoStack<Move> extends ArrayList<Move> 

Это использование Move в качестве типичного параметра типа, тогда как на самом деле вам вообще не нужен общий тип – вы просто хотите использовать Move как аргумент type для ArrayList<E>. Вы хотите:

public class UndoStack extends ArrayList<Move> 

Это должно решить проблему – хотя лично я настоятельно рекомендую использовать композицию вместо наследования здесь. (Другими словами, чтобы ваш тип UndoStack содержал ArrayList<Move> – или нечто подобное, а не подклассифицировал его.)

Кроме того, это никогда не сработает:

UndoStack undoStack;

private UndoStack() {
    undoStack = new UndoStack();
}

Это означает, что для создания UndoStack вам нужно создать еще один UndoStack… как вы ожидаете, что это произойдет? В настоящее время вы получаете исключение… зачем вам нужна переменная вообще?

Я создаю макетную базу данных сотрудников с использованием наследования и полиморфизма. При попытке переопределить методы суперкласса я столкнулся с следующими ошибками.

HourlyEmployee is not abstract and does not override abstract method resetWeek() in Employee
public class HourlyEmployee extends Employee
   ^
HourlyEmployee.java:43: error: method does not override or implement a method from a supertype
@Override
^
HourlyEmployee.java:54: error: method does not override or implement a method from a supertype
@Override
^
HourlyEmployee.java:60: error: method does not override or implement a method from a supertype
@Override
^
HourlyEmployee.java:66: error: method does not override or implement a method from a supertype
@Override

Вот мой подкласс класса Employee и HourlyEmployee.

public abstract class Employee
{
protected String firstName;
protected String lastName;
protected char middleInitial;
protected boolean fulltime;
private char gender;
private int employeeNum;

public Employee (String fn, String ln, char m, char g, int empNum, boolean ft)
{
    firstName = fn;
    lastName = ln;
    middleInitial = m;
    gender = g;
    employeeNum = empNum;
    fulltime = ft;
}

public int getEmployeeNumber()
{
    return employeeNum;
}

public void setEmployeeNumber(int empNum)
{
    while (empNum <= 10000 && empNum >= 99999)
    {
        System.out.print ("Invalid input, please try again: ");
    }

    if (empNum >= 10000 && empNum <= 99999)
    {
        employeeNum = empNum;
    }
}

public String getFirstName()
{
    return firstName;
}

public String getLastName()
{
    return lastName;
}

public char checkGender(char g)
{
    if (g != 'M' || g != 'F')
    {
        g = 'F';
    }
    return g;
}

public char getGender()
{
    return gender;
}


@Override
public boolean equals(Object e2)
{
    if (this.employeeNum == ((Employee)e2).employeeNum)
    {
        return true;
    }
    else
    {
        return false;
    }
}

@Override
public String toString()
{
    return employeeNum + "n" + lastName + ", " + firstName + "n" + "Gender:" + gender + "n" + "Status:" + fulltime + "n";
}

public abstract double caclulateWeeklyPay();

public abstract void annualRaise();

public abstract double holidayBonus();

public abstract void resetWeek();
}

Вот подкласс HourlyEmployee

public class HourlyEmployee extends Employee
{
private double wage;
private double hoursWorked;
private double additionalHours;

public HourlyEmployee(String fn, String ln, char m, char g, int empNum, boolean ft, double w, double h, double ahours)
{
    super (fn, ln, m, g, empNum, ft);
    wage = w;
    hoursWorked = h;
    hoursWorked = 0.0;
    additionalHours = ahours;
}

@Override
public String toString()
{
    return this.getEmployeeNumber() + "n" + lastName + ", " + firstName + middleInitial + "n" + "Gender: "
     + this.getGender() + "n" + "Status: " + fulltime + "n" + "Wage: " + wage + "n" + "Hours Worked: " + hoursWorked + "n";
}

   //@Override    
public double calculateWeeklyPay(double w, double h)
{
    if (h > 40)
    {
        w = w * 2;
    }

    return w * h;        
}

//@Override
public double annualRaise(double w)
{
    return (w * .05) + w;
}

//@Override
public double holidayBonus(double w)
{
    return w * 40;
}

//@Override
public double resetWeek(double h)
{
    h = 0.0;
    return h;
}

public double plusHoursWorked(double h, double ahours)
{
    while (h <= 0)
    {
        System.out.println("Invalid value entered, please try again");
    }

    h += ahours;

    return h;
}


}

Понравилась статья? Поделить с друзьями:
  • Rmse среднеквадратическая ошибка
  • Rmse root mean squared error
  • Rms удаленный доступ ошибка соединения
  • Rms ошибка соединения осталось попыток
  • Rms ошибка авторизации через систему безопасности сервера