equals() method?
shouldn´t one pass an object to equal?
String hej = pets.getBark();
if(hej.equals("woff"))
why are you able 开发者_如何学编程to pass a string woff?
If I understand your question properly you are wondering why a literal string value can be passed to a method that accepts an argument of type String
. This is because a string literal is a shorthand for a String
instance (either a new instance or a previously created instance that has been preserved by means of interning):
The
String
class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.
Under the hood, a string literal ( text inside quotes ) automatically is replaced by String instance. ( a string literal is shorthand for new String
)
That is why this code works: String hello = "hello";
So,
String hej = pets.getBark();
if( hej.equals( new String("woff") ) ) {}
is identical to the code you provided.
A quoted string is an object. It is an instance of the String class.
You can pass java.lang.String
, a subtype of java.lang.Object
, because Liskov substitution principle says so.
A literal string is still of type String.
精彩评论