package com.abstration.abstractclass;
abstract class CarTest
{
abstract void start();
abstract void accelerate();
abstract void brakes();
}
class Kia extends CarTest
{
void start()
{
System.out.println("Kia started");
}
void accelerate()
{
System.out.println("Kia accelerate");
}
void brakes()
{
System.out.println("kia stops");
}
class Audi extends CarTest
{
void start()
{
System.out.println("Audi started");
}
void accelerate()
{
System.out.println("Audi accelerate");
}
void brakes()
{
System.out.println("Audi stops");
}
}
public static class Driver
{
void driver(CarTest c)
{
c.start();
c.accelerate();
c.brakes();
}
}
public static void main(String args[])
{
Driver d = new Driver();
d.driver(new Kia());
d.driver(new Audi());
}
}
我面临的错误:-
1)No enclosing instance of type Kia is accessible. Must qualify the allocation with an enclosing instance of type Kia (e.g. x.new A() where x is an instance of Kia).
答案 0 :(得分:0)
在CarTest文件中,您应该具有:
abstract class CarTest
{
abstract void start();
abstract void accelerate();
abstract void brakes();
static class Kia extends CarTest
{
Kia() {
}
void start()
{
System.out.println("Kia started");
}
void accelerate()
{
System.out.println("Kia accelerate");
}
void brakes()
{
System.out.println("kia stops");
}
}
static class Audi extends CarTest
{
Audi() {
}
void start()
{
System.out.println("Audi started");
}
void accelerate()
{
System.out.println("Audi accelerate");
}
void brakes()
{
System.out.println("Audi stops");
}
}
}
请注意,起亚和奥迪现在是静态内部类,并且具有无参数构造函数。接下来,您应该放入一个ANOTHER文件,该类驱动程序如下所示:
class Driver
{
Driver(){}
void driver(CarTest c)
{
c.start();
c.accelerate();
c.brakes();
}
}
最后在一个THIRD文件中,放入您的主类,该主类将像这样调用其他类:
import (thePackage).CarTest.Audi;
import (thePackage).CarTest.Kia;
public class Main {
public static void main(String[] args) {
Driver d = new Driver();
d.driver(new Kia());
d.driver(new Audi());
}
}
重要的是将您的类分为不同的文件,而不是将所有内容都保存在一个大文件中。它使阅读,修复和实际执行任何操作变得混乱。您还需要确保为要实例化的类创建构造函数,您将在它们上使用new
。另外,请确保所有这些文件都在同一软件包中。