在Java类中,可以定义一个方法final,以标记此方法可能不会被覆盖:
public class Thingy {
public Thingy() { ... }
public int operationA() {...}
/** this method does @return That and is final. */
public final int getThat() { ...}
}
Run Code Online (Sandbox Code Playgroud)
这很清楚,它可能有助于防止意外覆盖,或者表现 - 但这不是我的问题.
我的问题是:从OOP的角度来看,我理解通过定义一个方法final,类设计者承诺这个方法将始终如所描述或隐含的那样工作.但是,这通常可能超出了班级作者的影响,如果该方法所做的事情比传递财产更复杂.
句法约束对我来说很清楚,但OOP意义上的含义是什么?final大多数班级作者在这个意义上是否正确使用?
final方法承诺什么样的"合同" ?
私有方法最终是否有益?这会改善表现吗?
我认为"私人决赛"没有多大意义,因为私有方法无法被覆盖.所以方法查找应该像使用final时一样高效.
私有帮助方法是静态的(如果可能的话)会更好吗?
什么是最好用的?
private Result doSomething()
private final Result doSomething()
private static Result doSomething()
private static final Result doSomething()
Run Code Online (Sandbox Code Playgroud) 我是Java新手.我想知道在私有类中使用公共构造函数是什么.类中的私有类可以从同一个类初始化然后将私有类的构造函数公开的用途是什么?
public class MainActivity extends Activity {
private class AcceptThread extends Thread {
public AcceptThread() {
}
}
}
Run Code Online (Sandbox Code Playgroud) 我在内部类中有一个私有方法,它是私有的我想使用SafeVarargs注释.但是,我需要有静态或最终方法.为什么私有方法也必须是最终的?这不是多余的吗?
我有一个带有私有 @Scheduled 方法的简单 Spring Boot 应用程序:
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Scheduled(fixedRate = 1000)
private void scheduledTask() {
System.out.println("Scheduled task");
}
}
Run Code Online (Sandbox Code Playgroud)
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-spring-legacy</artifactId>
<version>1.1.1</version>
</dependency>
<dependency> …Run Code Online (Sandbox Code Playgroud)