Java中的"new"关键字(Android):D

Bla*_*ama 1 java oop android

我已经阅读了一些参考文献,我认为我理解在OOP语言中使用"新"关键字(但我没有!)

所以,我无法理解这行代码,我从图坦卡蒙在得到它thenewboston:

ourBrow = (WebView) findViewById(R.id.wvBrowser);
ourBrow.setWebViewClient(new OurViewClient());
Run Code Online (Sandbox Code Playgroud)

因此,该setWebViewClient();方法需要一个WebViewClient的params.认为我不明白的是,为什么我们需要在这里添加"new"关键字?注意,这OurViewClient()是我们制作和扩展的类WebViewClient.

对不起,如果我问这个问题的方式让你感到困惑,因为我现在也迷惑了@ _ @

谢谢大家!:d

注意:英语不是我的本地语言,所以如果我犯了一些错误就很抱歉:D

aro*_*oth 5

OurViewClient是你做的课. OurViewClient()是该类的构造函数,它接受0个参数.并且该setWebViewClient()方法需要WebViewClient 实例作为其参数.

因此,new运算符有效地分配了OurViewClient类的新实例,然后在该实例上调用默认的0参数构造函数,返回创建的对象.使用new是唯一可以创建ObjectJava 实例的方法,除了更高级的主题,如反射或使用类似的东西sun.misc.Unsafe,还有一些以内置类型/自动装箱为中心的例外(例如String s = "str";Integer num = 7;).

请注意,以下代码基本上等同于您拥有的代码:

WebViewClient client = new OurViewClient();
ourBrow = (WebView) findViewById(R.id.wvBrowser);
ourBrow.setWebViewClient(client);
Run Code Online (Sandbox Code Playgroud)

另请注意以下内容无效:

WebViewClient client = OurViewClient();  //can't invoke a constructor without using 'new'
WebViewClient client = OurViewClient;    //can't assign the class
WebViewClient client;  //valid syntax, but 'client' will be null
Run Code Online (Sandbox Code Playgroud)