Classes and Objects in Java
Fields, methods, constructors, access modifiers and the static keyword.
Easy
public class Resistor {
private final double ohms; // field
public Resistor(double ohms) { // constructor
this.ohms = ohms;
}
public double current(double volts) { // method
return volts / ohms;
}
public static double series(double a, double b) { return a + b; } // belongs to the class
}
Access modifiers: private (this class), package-private (default), protected (subclasses), public (everyone). Use getters/setters instead of public fields.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.