1

Im trying to create a instance of the subclass ''smycken'' but it does not seem to work as ''namn'' in the parameter gets an error.

public abstract class Värdesaker {

    String namn;
    double värde;
    double moms = 1.25;

    public static void main(String[] args) {

        Värdesaker v = new smycken(namn, false, 0);

    }

    class smycken extends Värdesaker {

        double vikt, ädelstenar;

        public smycken(String namn, boolean guld, int ädelstenar) {
            this.namn = namn;
            this.ädelstenar = ädelstenar;
            if (guld)
                this.värde = (2000 + (ädelstenar * 500)) * moms;
            else
                this.värde = (500 + (ädelstenar * 500)) * moms;

        }
Pie
  • 584
  • 1
  • 6
  • 22
  • What is the error you get? – Sid May 01 '19 at 12:20
  • First of all, you have to mark your class smycken as static so it can be used from the static main method. You are not creating a local variable in the main method. Which can be passed on as an argument to the constructor of your subclass. Namn variable is not accessible as its member variable of the class – Vikram Patil May 01 '19 at 12:22
  • protected String namn; protected double värde; protected double moms; Also, call super() first from your child constructor. As the comment above states, the child cannot see the private variables of the father. – aran May 01 '19 at 12:24
  • While it is really a *subclass*, the issue comes from being an *inner class*, perhaps *nested*. Then you can find countless topics: https://stackoverflow.com/questions/4070716/instantiating-inner-class and https://stackoverflow.com/questions/12690128/how-to-instantiate-non-static-inner-class-within-a-static-method being two of them. – tevemadar May 01 '19 at 12:45

1 Answers1

0

I have modified your code as follows. It seems to work. Following things are required

  1. Changing access specifier to protected for member variables of super class Värdesaker ( Or you can provide getter-setters for access to private variables)
  2. Mark smycken as static
  3. The main method cannot access non-static, non-public member variables.So you have to instantiate your arguments or create as before using in constructor.

// modified class

  public abstract class Värdesaker {
  protected String namn;
  protected double värde;
  protected double moms = 1.25;

  public static void main(String[] args)
  {

    Värdesaker v = new smycken("Test", false, 0);

  }

  static class smycken extends Värdesaker
  {

    double vikt, ädelstenar;

    public smycken(String namn, boolean guld, int ädelstenar)
    {
      this.namn = namn;
      this.ädelstenar = ädelstenar;
      if (guld) {
        this.värde = (2000 + (ädelstenar * 500)) * moms;
      } else {
        this.värde = (500 + (ädelstenar * 500)) * moms;
      }

    }
  }
}
Vikram Patil
  • 628
  • 6
  • 20