简体   繁体   English

声明子类的对象

[英]Declaring object of subclass

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. 我试图创建子类“ smycken”的实例,但由于参数中的“ namn”出现错误,因此似乎无法正常工作。

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;

        }

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) 将访问说明符更改为超类Värdesaker的成员变量的受保护(或者您可以提供用于获取私有变量的getter-setter方法)
  2. Mark smycken as static 将smycken标记为静态
  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. main方法无法访问非静态,非公共成员变量,因此您必须实例化参数或像以前在构造函数中使用一样创建。

// 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;
      }

    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM