我有一个接口,它有一个自身的方法,例如
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.bundle.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<a href="#" onClick="openFeedback('getBootstrap')">Klik hier om de website te bekijken</a>
<div class="modal fade" id="iframe_feedback" style="padding-top: 20px;">
<i class="ion-close-round close-modal" style="position: fixed; right: 40px; font-size: 32px; color: red; top: 40px; cursor: pointer; z-index: 1700;" onClick="closeModal()">close</i>
<div class="modal-dialog" style="max-width: 90%; margin: 0 auto; overflow: scroll;">
<div id="clip" style="overflow:scroll;">
<iframe src="/dashboard" style=" width:2600px; height: 1600px;"></iframe>
</div>
</div>
</div>
现在,我希望以这样一种方式实现这个界面,即车辆只能撞到自己类型的车辆。也就是说,我想要像
这样的东西public interface Vehicle {
void bump(Vehicle other);
}
但是BumperCars和Trains之间的碰撞什么都不做,即使两个类都必须实现bump(Vehicle)。实现这一目标的最佳方法是什么?
答案 0 :(得分:2)
由于Java缺乏在类中使用self
类型的可能性,因此称为&#34;模拟自我类型&#34;通常用于此:
abstract class Vehicle<T extends Vehicle<T>> {
public abstract void bump(T other);
}
public class Car extends Vehicle<Car> {
@Override public void bump(Car other) {}
}
唯一需要注意的是,总是要在类声明中指定类型。
在核心Java库中,模拟自我类型用法的一个示例是Enum类。
答案 1 :(得分:0)
我对“可能的重复评论”中提到的解决方案不太满意,所以我将展示如何做到这一点。
首先,正如我在评论中所说,你没有从界面覆盖该方法。签名需要匹配。
为了做到这一点,请使用界面中的签名创建一个函数。在该方法中,使用instanceof
运算符检查您的对象是否来自正确的类型。像这样:
public class BumperCar implements Vehicle {
public void bump(Vehicle other){
if(other instanceof BumperCar) {
System.out.println("...");
}
}
}
答案 2 :(得分:0)
您需要使用自引用泛型类型:
#settings.py
import os
DJ_PROJECT_DIR = os.path.dirname(__file__)
BASE_DIR = os.path.dirname(DJ_PROJECT_DIR)
WSGI_DIR = os.path.dirname(BASE_DIR)
REPO_DIR = os.path.dirname(WSGI_DIR)
DATA_DIR = os.environ.get('OPENSHIFT_DATA_DIR', BASE_DIR)
import sys
sys.path.append(os.path.join(REPO_DIR, 'libs'))
import json
try:
with open(os.path.join(DATA_DIR, 'secrets.json')) as handle:
SECRETS = json.load(handle)
except IOError:
SECRETS = { 'secret_key': 'a' }
....
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
# GETTING-STARTED: change 'db.sqlite3' to your sqlite3 database:
'NAME': os.path.join(DATA_DIR, 'db.sqlite3'),
},
'db2': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(DATA_DIR, 'db2.sqlite3'),
},
'db3': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(DATA_DIR, 'db3.sqlite3'),
}
}