gpt4 book ai didi

java - 泛型中类型参数中的常量

转载 作者:行者123 更新时间:2023-11-29 07:12:46 24 4
gpt4 key购买 nike

我正在阅读 Thinking in java 第 4 版,我遇到了这段代码

class SuperHero<POWER extends SuperPower> {
POWER power;

SuperHero(POWER power) {
this.power = power;
}

POWER getPower() {
return power;
}
}

我查看了这段代码的整个类定义,但似乎找不到关键字 POWER,所以我假设它是一个常量?在这种情况下,“POWER”实际上是什么?

这是整个类的定义

package tij4.generics;

//: generics/EpicBattle.java
//Demonstrating bounds in Java generics.
import java.util.*;

//Marker Interface
interface SuperPower {
}

interface XRayVision extends SuperPower {
void seeThroughWalls();
}

interface SuperHearing extends SuperPower {
void hearSubtleNoises();
}

interface SuperSmell extends SuperPower {
void trackBySmell();
}

class SuperHero<POWER extends SuperPower> {
POWER power;

SuperHero(POWER power) {
this.power = power;
}

POWER getPower() {
return power;
}
}

class SuperSleuth<POWER extends XRayVision> extends SuperHero<POWER> {
SuperSleuth(POWER power) {
super(power);
}

void see() {
power.seeThroughWalls();
}
}

class CanineHero<POWER extends SuperHearing & SuperSmell> extends
SuperHero<POWER> {
CanineHero(POWER power) {
super(power);
}

void hear() {
power.hearSubtleNoises();
}

void smell() {
power.trackBySmell();
}
}

class SuperHearSmell implements SuperHearing, SuperSmell {
public void hearSubtleNoises() {
}

public void trackBySmell() {
}
}

class DogBoy extends CanineHero<SuperHearSmell> {
DogBoy() {
super(new SuperHearSmell());
}
}

public class EpicBattle {
// Bounds in generic methods:
static <POWER extends SuperHearing> void useSuperHearing(
SuperHero<POWER> hero) {
hero.getPower().hearSubtleNoises();
}

static <POWER extends SuperHearing & SuperSmell> void superFind(
SuperHero<POWER> hero) {
hero.getPower().hearSubtleNoises();
hero.getPower().trackBySmell();
}

public static void main(String[] args) {
DogBoy dogBoy = new DogBoy();
useSuperHearing(dogBoy);
superFind(dogBoy);
// You can do this:
List<? extends SuperHearing> audioBoys;
// But you can't do this:
// List<? extends SuperHearing & SuperSmell> dogBoys;
}
} // /:~

添加信息:我还查看了这个包中包含的不同类。并且它们都没有定义枚举“POWER”

最佳答案

它只是一个通用的类型名称,就像T一样。在java.util.List<T> .作者只是为这种类型选择了一个更大的名字。

关于java - 泛型中类型参数中的常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12275190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com