[英]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? 为什么您可以传递字符串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
. 如果我正确理解了您的问题,您想知道为什么可以将文字字符串值传递给接受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): 这是因为字符串文字是String
实例(通过实例保留的新实例或以前创建的实例)的简写:
The
String
class represents character strings.String
类表示字符串。 All string literals in Java programs, such as "abc", are implemented as instances of this class. Java程序中的所有字符串文字(例如“ abc”)都实现为此类的实例。
A quoted string is an object. 带引号的字符串是一个对象。 It is an instance of the String class. 它是String类的一个实例。
Under the hood, a string literal ( text inside quotes ) automatically is replaced by String instance. 在幕后,一个字符串文字(引号内的文本)自动替换为String实例。 ( a string literal is shorthand for new String
) (字符串文字是new String
简写)
That is why this code works: String hello = "hello";
这就是为什么这段代码起作用的原因: String hello = "hello";
So, 所以,
String hej = pets.getBark();
if( hej.equals( new String("woff") ) ) {}
is identical to the code you provided. 与您提供的代码相同。
您可以传递java.lang.String
的子类型java.lang.Object
,因为Liskov替换原理如此。
文字字符串仍为String类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.