Android Build a Simple Android App with Java Improving Our Code Simple Refactoring: Using a New Class

Uzair Khan
Uzair Khan
1,628 Points

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

not able to fix this error

public class FactBook {

    // fields or member variables


    private  String[] facts = {
"Pakistan is the world’s first Islamic country to attain nuclear power.",

 "Pakistan has the highest paved international road – The Karakoram Highway (KKH).",

  "Pakistan has the largest canal-based irrigation system in the world.",

"The name Pakistan means ‘land of the pure’ in Persian and Urdu.",

 "Just two people have won the Nobel Prize from Pakistan. Malala Yousafzai for Peace in 2014 and Abdus Salam for Physics in 1979.",

"Sugarcane juice is the national drink of Pakistan. In Pakistan, it is also known as (roh). ",

"K-2 (Chagori) is the highest mountain peak in Pakistan and the second highest in the world.",

"The ‘Khewra Salt Mine’ in Pakistan is the second largest and oldest salt mine in the world.",

 "The world’s seventh-largest collection of scientists and engineers is from Pakistan.",

 "Islamabad, Pakistan is ranked the second most beautiful capital in the world."};


    // methods (actions that object can take )


    @Override
    public String getFact(){

        // Randomly sellect a fact
        Random randomGenerator = new Random();
        int randomNumber = randomGenerator.nextInt(facts.length);
        return facts[randomNumber];

    };
}

1 Answer

The problem here is the @Override annotation and the concept of inheritance. Just as we inherit genes from our parents, classes inherit fields and methods from their parent class (or superclass). When we want to define a specific implementation of one of these inherited methods in a child class, we use the @Override annotation then make the necessary adjustments in that method.

Here, you do not have a parent class declared: your class declaration is not (for example)

public class FactBook extends SomeSuperclass {

so here the parent class is the mother of all classes: the Object class. The getFact() method is a new method declared in this FactBook class (it's not a method of the Object class), so you do not need to override it. To have a list of all the methods your class inherits, just call Ctrl+O in Android Studio.

tl;dr You do not need the @Override annotation here as your method is not inherited from a parent/superclass, but is a new method declared in this FactBook class.

Inheritance is an important concept in Android Development (and all Object-Oriented Programming languages). I see that Treehouse has recently launched a new course on it: https://teamtreehouse.com/library/inheritance-in-java Hope that helps.