具有来自继承的抽象类的值的构造函数,该类实现一个接口

时间:2018-07-23 19:53:10

标签: java inheritance constructor interface abstract-class

我正在尝试通过构造函数实例化Car类型的对象,并且收到以下2个错误:“静态字段Vehicle.name应该以静态方式访问”和“无法分配最终字段Vehicle.name”在构造函数上。变量,但numWheels除外。

@Bean(name = "writeDataSource")
    @ConfigurationProperties(prefix = "datasource.write")
    public DataSource writeDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "readDataSource")
    @ConfigurationProperties(prefix = "datasource.read")
    @Primary
    public DataSource readDataSource() {
        return DataSourceBuilder.create().build();
    }

@Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier("dataSource") DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
        emfb.setDataSource(dataSource);
        emfb.setPackagesToScan("com.abc");        
        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        emfb.setJpaVendorAdapter(jpaVendorAdapter);

        /** Setting additional properties */
        Properties props = new Properties();
        props.put("hibernate.show_sql", "true");
        props.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        props.put("hibernate.ejb.interceptor", hibernateInterceptor());
        props.put("hibernate.id.new_generator_mappings","false");
        emfb.setJpaProperties(props);

        return emfb;
    }

1 个答案:

答案 0 :(得分:4)

如果在接口上定义字段,则认为它是常量。它是公共的,静态的和最终的。静态意味着,在每个对象实例中,没有一个单独的成员变量,而该类只有一个。而最终意味着该价值永远无法改变。因此,在这种情况下,名称只能是长度为0的字符串,并且属于接口,而不属于任何实现Vehicle的实例。

如果希望将它们作为实例字段,请按照定义numWheels的方式对其进行定义,然后将它们放在类中,而不是在接口中。在这里,您似乎要使Vehicle成为LandVehicle扩展的超类,所以就使其成为一个类。

接口描述了对象具有的功能,但未提供实现(默认方法除外,暂时不要使用默认方法!)。在接口中添加常量的功能很方便,在某些情况下,指定在调用该接口的方法时可能会使用的常量很有用。使用接口来指定您的对象承诺实现的契约,该契约将在其中实现接口的方法。请参见JDK中的接口示例,例如java.lang.CharSequence和java.util.List。