匿名类是未命名的类,非常适合就地定义和实例化类或接口的实现,而不需要额外的文件。 其一次性使用性质阻碍了其重复使用。与本地类(声明)不同,匿名类是生成单个对象的表达式,可分配给变量。
当一个类仅使用一次时,例如在定义接口或抽象类的特定方法时,它们特别有用。 它在 Java Swing 中的应用很频繁,有 event listeners
或 lambda 函数(箭头函数)。
一个奇怪的事实是,Java 编译器为它们分配一个自动名称(例如 ClaseContenedora.class
),由包含类的名称和指示其位置的数字组成。
语法:
作为一个表达式,其语法类似于构造函数的调用,但它包含定义类结构的代码块:
ClaseOInterfaz nombreVariable = new ClaseOInterfaz() { // Cuerpo de la clase anónima };
关键组件是:
- 运算符
new
。 - 要扩展的类的名称或要实现的接口。
- 带构造函数参数的括号(如果有的话),就像实例化普通类时一样。 在接口中,括号是空的。
- 锁定类主体的键。
- 它在一行中声明和实例化,存储在变量中。
匿名类的类型:
- 课程的扩展。
- 抽象类的扩展。
- 接口的实现。
- 方法的参数。
示例:
1。延长一堂课:
public class Carro { public void tipoMotor() { System.out.println("Motor de combustión interna"); } } public class Main { public static void main(String[] args) { Carro carroCombustion = new Carro(); Carro carroElectrico = new Carro() { @Override public void tipoMotor() { System.out.println("Motor eléctrico"); } }; carroCombustion.tipoMotor(); // Motor de combustión interna carroElectrico.tipoMotor(); // Motor eléctrico } }
2。抽象类的扩展:
public abstract class ConexionBD { public abstract void obtenerConexion(); } public class Main { public static void main(String[] args) { ConexionBD conexionMySQL = new ConexionBD() { @Override public void obtenerConexion() { System.out.println("Conexión a MySQL"); } }; ConexionBD conexionPostgreSQL = new ConexionBD() { @Override public void obtenerConexion() { System.out.println("Conexión a PostgreSQL"); } }; conexionMySQL.obtenerConexion(); // Conexión a MySQL conexionPostgreSQL.obtenerConexion(); // Conexión a PostgreSQL } }
3。接口的实现:
import java.util.Arrays; import java.util.Comparator; import java.util.List; public class Main { public static void main(String[] args) { List<Integer> numeros = Arrays.asList(5, 10, 56, 3, 2, 1, 0); numeros.sort(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }); System.out.println(numeros); // [56, 10, 5, 3, 2, 1, 0] } }
4。方法的参数:
public class Main { public static void main(String[] args) { Thread hilo = new Thread(new Runnable() { @Override public void run() { while (true) { System.out.println("Hola, soy un hilo"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); hilo.start(); } }
优点:
- 仅在需要时创建对象。
- 修改没有子类的类或接口的行为。
- 更简洁、可读的代码。
- 避免额外的文件,从而节省时间。
范围:
与普通类类似,可以访问容器作用域的局部变量,但有不能声明静态初始化器或接口的限制,以及访问非最终或有效最终局部变量的限制。
结论:
匿名类是 Java 中一个强大且多功能的工具,对于独特而简洁的实现非常有用。 它的使用虽然有时是隐式的,但可以简化代码并提高效率。 更多信息请参阅 Java 官方文档。
以上是Java 中的匿名类的详细内容。更多信息请关注PHP中文网其他相关文章!

Java在不同操作系统上的表现存在细微差异。1)JVM实现不同,如HotSpot、OpenJDK,影响性能和垃圾回收。2)文件系统结构和路径分隔符不同,需使用Java标准库处理。3)网络协议实现差异影响网络性能。4)GUI组件外观和行为在不同系统上有别。通过使用标准库和虚拟机测试,可减少这些差异的影响,确保Java程序稳定运行。

javaoffersrobustobject-IentiendedProgrammming(OOP)和Top-Notchsecurityfeatures.1)OopinjavainCludesClasses,对象,继承,多态性,和列出,andeclingfleximaintainablesys.ss.2)SecurityFeateTuersLudEtersludEterMachine(

JavaScriptandJavahavedistinctstrengths:JavaScriptexcelsindynamictypingandasynchronousprogramming,whileJavaisrobustwithstrongOOPandtyping.1)JavaScript'sdynamicnatureallowsforrapiddevelopmentandprototyping,withasync/awaitfornon-blockingI/O.2)Java'sOOPf

JAVAACHIEVESPLATFORMINDEPENTENCETHROUGHJAVAVIRTAILMACHINE(JVM)和BYTECODE.1)THEJVMINTERPRETSBBYTECODE,允许theingthesmecodetorunonanyanyanyanyplatformwithajvm.2)

Java'splatFormIndependecemeanSapplicationsCanrunonAnyPlatFormWithAjvm,使“ Writeonce,RunanyWhere”。

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生产性。1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允许CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

禅工作室 13.0.1
功能强大的PHP集成开发环境

WebStorm Mac版
好用的JavaScript开发工具

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

SublimeText3汉化版
中文版,非常好用

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具