Question

What is wrong with the following Java Code. public class TestEdible { abstract class Animal {...

What is wrong with the following Java Code.

public class TestEdible
{
    abstract class Animal
    {
        /** Return animal sound */
        public abstract String sound();
    }

    class Chicken extends Animal implements Edible
    {
        @Override
        public String howToEat()
        {
            return "Chicken: Fry it";
        }

        @Override
        public String sound()
        {
            return "Chicken: cock-a-doodle-doo";
        }
    }

    class Tiger extends Animal
    {
        @Override
        public String sound()
        {
            return "Tiger: RROOAARR";
        }
    }

    abstract class Fruit implements Edible
    {
        // Data fields, constructors, and methods omitted here
    }

    class Apple extends Fruit
    {
        @Override
        public String howToEat()
        {
            return "Apple: Make apple cider";
        }
    }

    class Orange extends Fruit
    {
        @Override
        public String howToEat()
        {
            return "Orange: Make orange juice";
        }
    }

    public static void main(String[] args)
    {
        Object[] objects = {new Tiger(), new Chicken(), new Apple()};
        for (int i = 0; i < objects.length; i++)
        {
            if (objects[i] instanceof Edible)
            {
                System.out.println(((Edible)objects[i]).howToEat());
            }

            if (objects[i] instanceof Animal)
            {
                System.out.println(((Animal)objects[i]).sound());
            }
        }
    }
}

The error occurs at the line:

Object[] objects = {new Tiger(), new Chicken(), new Apple()};

With the message:

Error:(58, 29) java: non-static variable this cannot be referenced from a static context

Error:(58, 42) java: non-static variable this cannot be referenced from a static context

Error:(58, 57) java: non-static variable this cannot be referenced from a static context

The code is from "Introduction to a Java Programming 9th Edition"

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hey, I have given my best to solve your query and with a proper explanation, if you have still any doubt feel free to comment and if my solution was helpful then leave a like.

I can understand your frustration and this is very common when you start learning a new programming language nowhere you won't believe how small was the correction and that small correction was stopping you from the solution.

It was all because of a parenthesis { }. I know you must be wondering what I am saying just look at the snapshot I have added.

Inside the class, TestEdible just keep your main method and then close that class and the rest of the code will be outside of class TestEdible like this

// image

U ĐWNE 2. public class TestEdible { public static void main(String[] args) { Object[] objects = {new Tiger(), new Chicken(),

// image

30 31 } } 33 - class Tiger extends Animal { 34 @Override public String sound() { 36 return Tiger: RROOAARR; 37 } 38 } 35 40

and check now you will get your expected output something like this

ODK8>javac TestEdible.java Compiled successful UDK8>java TestEdible Tiger: RROOAARR Chicken: Fry it Chicken: cock-a-doodle-do

Now let me tell you the concept behind this problem and what your error actually means.

It is a simple concept of static as you must know that we cannot make a reference to a non-static method from a static method and your main method is static. This concept will irritate you for a while in the beginning but you must know the difference between static and nonstatic.

Static Variables belongs to the class and its value will always remain the same for all instance and when a class is loaded into JVM a static variable gets initialized and see the main method do we need to create any instance to reference it through any variable no because it is static.

We need to create an instance of the class as an object and then only we will be able to access methods and any variables of that class that are not declared static. Once our java program starts with the main function we can access any variable having modifier static as they exist as part of the class. Then for those variables and methods of the class which are not static and outside of the main method will not be used until we create an instance of the class as an object within the main method.

Add a comment
Know the answer?
Add Answer to:
What is wrong with the following Java Code. public class TestEdible { abstract class Animal {...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • PRG/421 Week One Analyze Assignment – Analyzing a Java™Program Containing Abstract and Derived Classes 1.    What is...

    PRG/421 Week One Analyze Assignment – Analyzing a Java™Program Containing Abstract and Derived Classes 1.    What is the output of the program as it is written? (Program begins on p. 2) 2. Why would a programmer choose to define a method in an abstract class (such as the Animal constructor method or the getName()method in the code example) vs. defining a method as abstract (such as the makeSound()method in the example)? /********************************************************************** *           Program:          PRG/421 Week 1 Analyze Assignment *           Purpose:         Analyze the coding for...

  • (JAVA NetBeans) Write programs in java Example 10.21-24 //Animal.java /** Animal class * Anderson. Franceschi */...

    (JAVA NetBeans) Write programs in java Example 10.21-24 //Animal.java /** Animal class * Anderson. Franceschi */ import java.awt.Graphics; public abstract class Animal { private int x; // x position private int y; // y position private String ID; // animal ID /** default constructor * Sets ID to empty String */ public Animal( ) { ID = ""; } /** Constructor * @param rID Animal ID * @param rX x position * @param rY y position */ public Animal( String...

  • What is output? public abstract class People { protected string name; protected int age; public abstract...

    What is output? public abstract class People { protected string name; protected int age; public abstract void PrintInfo(); public void PrintInformation() { System.out.println("In Base Class People"); public class Teacher extends People { private int experience; public void PrintInfo() { System.out.println("In Child Class Teacher"); public class Principal extends Teacher { public void PrintInformation() { System.out.println("In Child Class Principal"); public static void main(String args[]) { Principal tim; tim = new Principal(); tim.PrintInfo(); In Base Class People Error: Compiler error In Child Class...

  • What is wrong with this Code? Fix the code errors to run correctly without error. There...

    What is wrong with this Code? Fix the code errors to run correctly without error. There are seven parts for one code, all are small code segments for one question. All the 'pets' need to 'speak', every sheet of code is connected. Four do need need any Debugging, three do have problems that need to be fixed. Does not need Debugging: public class Bird extends Pet { public Bird(String name) { super(name); } public void saySomething(){} } public class Cat...

  • In java. You are provided an abstract class called MyAbstract. You can only modify the writeFile...

    In java. You are provided an abstract class called MyAbstract. You can only modify the writeFile () class. You are provided another class called Finally you are provided the file you must read from in the MyAbstract class. You will need to extend MyAbstract to MyTestClass. You should have the following outputs. The content of myData employee avg salary number of employees File that was created in myFile() Everything I was provided is listed already. l. Servers ary 1 35...

  • I Need UML Design for the following Java code: Colorable interface: public interface Colorable { //a...

    I Need UML Design for the following Java code: Colorable interface: public interface Colorable { //a void method named howToColor(). void howToColor(); } GeometricObject class: public class GeometricObject { } Sqaure class: public class Square extends GeometricObject implements Colorable{ //side variable of Square double side;    //Implementing howToColor() @Override public void howToColor() { System.out.println("Color all four sides."); }    //setter and getter methods for Square public void setSide(double side) { this.side = side; }    public double getSide() { return...

  • what is abstract class in java? for example, abstract class animal and subclass cat which extends...

    what is abstract class in java? for example, abstract class animal and subclass cat which extends abstract class, and the test class which will call cat class to show if it yawns, scratch and whatnot. I used to create class animal but it was not abstract, so I am not sure the purpose of it. Another question, I created interface, by right clicking the package, I think the teacher saying interface is acts independent? and not part of hierarchy like...

  • In Java. Please use the provided code Homework 5 Code: public class Hw05Source { public static...

    In Java. Please use the provided code Homework 5 Code: public class Hw05Source { public static void main(String[] args) { String[] equations ={"Divide 100.0 50.0", "Add 25.0 92.0", "Subtract 225.0 17.0", "Multiply 11.0 3.0"}; CalculateHelper helper= new CalculateHelper(); for (int i = 0;i { helper.process(equations[i]); helper.calculate(); System.out.println(helper); } } } //========================================== public class MathEquation { double leftValue; double rightValue; double result; char opCode='a'; private MathEquation(){ } public MathEquation(char opCode) { this(); this.opCode = opCode; } public MathEquation(char opCode,double leftVal,double rightValue){...

  • The current code I have is the following: package uml; public class uml {        public...

    The current code I have is the following: package uml; public class uml {        public static void main(String[] args) {              // TODO Auto-generated method stub        } } class Account { private String accountID; public Account(String accountID) { this.accountID = accountID; } public String getAccountID() { return accountID; } public void setAccountID(String accountID) { this.accountID = accountID; } @Override public String toString() { return "Account [accountID=" + accountID + "]"; } } class SuppliesAccount extends Account { private...

  • D Question9 Which of the following represents the output of the following code segment? abstract class...

    D Question9 Which of the following represents the output of the following code segment? abstract class Base Base0System.out.println("Base Constructor Called"); abstract void fun: class Derived extends Base Constructor Called"): fun) called"): ) class MainClass Derived0 System.out.println("Derived void fun [System.out.printin/"Derived public static void main(String args) Derived d = new Derived@; O Print "Derived Constructor Called then print Base Constructor Called O Print "Base Constructor Called then print Derived Constructor Called" O We must write @override above the fun) method in Derived...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT