rspec/rules/S3434/java/rule.adoc

51 lines
1.5 KiB
Plaintext
Raw Normal View History

Shadowing parent class ``++static++`` methods by creating methods in child classes with the same signatures can result in seemingly strange behavior if an instance of the child class is cast to the parent class and the static method is invoked using a reference to the child class. In such cases, the parent class' code will be executed instead of the code in the child class, confusing callers and potentially causing hard-to-find bugs. Instead the child class method should be renamed.
2020-06-30 12:48:39 +02:00
== Noncompliant Code Example
----
public class Fruit {
public static Double getCost() {
return 3.5;
}
}
public class Raspberry extends Fruit {
public static Double GetCost() // Noncompliant {
return 7.5;
}
}
// ...
var r = new Raspberry();
var f = (Fruit) r;
System.out.println(r.GetCost()); // prints 7.5
System.out.println(f.GetCost()); // prints 3.5; there's only one instance but different code executes depending on cast
----
== Compliant Solution
----
public class Fruit {
public static DoubleGetCost() {
return 3.5;
}
}
public class Raspberry extends Fruit {
public static Double GetInflatedCost() {
return 7.5;
}
}
// ...
var r = new Raspberry();
var f = (Fruit) r;
System.out.println(r.GetCost()); // prints 3.5, Raspberry.GetCost() would be even better
System.out.println(f.GetCost()); // prints 3.5; same code executes every time
System.out.println(r.GetInflatedCost()); // prints 7.5, Raspberry.GetInflatedCost() would be even better
----
== Exceptions
2021-01-27 13:42:22 +01:00
This rule ignores ``++private++`` parent class members.