自学编程者的Java面向对象疑问:接口与类实现问题咨询
Hey Richard, let's work through this step by step to get your class and variables properly structured—you're already off to a great start by using interfaces to define behavior! 🚀
1. Fix Typos & Complete the Implementation
First, let's clean up the partial code you shared and fix a couple of small issues:
- There's a typo in your class variable (
pitc→pitch) - A spelling error in
occuranceTime(correct isoccurrenceTime—small detail but important for readability) - We should encapsulate your variables (use
privateaccess modifier) to follow core OOP principles
Here's the completed, corrected class:
public class Pitch implements PitchInterface{ // Private variables enforce encapsulation—external code can't modify these directly private float occurrenceTime; // Fixed spelling private float pitch; // Implement interface methods with @Override to catch signature errors early @Override public void setOccuranceTime(float occuranceTime) { // Keep the parameter name matching the interface, assign to our corrected variable this.occurrenceTime = occuranceTime; } @Override public float getOccuranceTime() { return occurrenceTime; } @Override public void setPitch(float pitch) { this.pitch = pitch; } @Override public float getPitch() { return pitch; } }
2. Core Principles for Clean Classes & Variables
Let's break down the key rules you're applying here (and should keep using):
- Encapsulation: Using
privatefor member variables means you control how data is accessed/modified. Later, you could add validation (e.g., prevent negative pitch values) directly in the setter methods without changing external code. - Naming Consistency: Stick to Java's camelCase for variables, and fix spelling to avoid confusion for anyone reading your code (including future you!).
- Interface Contracts: By defining
PitchInterface, you've created a clear set of behaviors that any "pitch-like" class must implement. This makes your code flexible—if you later build aDynamicPitchclass, it can implement the same interface and work with existing code that expects aPitchInterface. - @Override Annotation: This tells the compiler to verify you're correctly implementing the interface method. It prevents mistakes like misspelling method names or using wrong parameter types.
3. Optional Enhancements for Robustness
If you want to level up your class even more, consider these tweaks:
- Add parameter validation in setters:
@Override public void setPitch(float pitch) { if (pitch < 0) { throw new IllegalArgumentException("Pitch cannot be negative"); } this.pitch = pitch; } - Override
toString()for easier debugging:@Override public String toString() { return "Pitch{" + "occurrenceTime=" + occurrenceTime + ", pitch=" + pitch + '}'; }
内容的提问来源于stack exchange,提问作者Richard
相关产品推荐
相关产品推荐

