Head First Java 笔记3

2020-02-06  本文已影响0人  Wilbur_

Instance Variables

Instance variables are declared inside a class but not inside a method. They represent the "fields" that each individual object has (which can be filled with different values for each instance of the class). Instance variables live inside the object they belong to.

Local variables local variables are devlared inside a method, including method parameters. They're temporary, and live only as long as the method is on the stack (in other words, as long as the method has not reached the closing curly brace).

Head first java p236

Constructor

A constructor does look and feel a lot like a method, but it's not a method. It's got the code that runs when you say new. In other words. the code that runs when you instantiate an object.

The only way to invoke a constructor is with the keyword new followed by the class name. The JVM finds that class and invokes the constructor in that class. (OK, technically this isn;t the only way to invoke a constructor. But it's the only way to do it from outside a constructor. You can call a constructor from within another constructor, with restrictions, but we'll get into all that later in the chapter.)

A constructor has the code that runs when you instantiate an object. in other words, the code that runs when you say new on a class type.
Every class you create has a constructor, even if you don't write it yourself.

The key feature fo a constructor is that it runs before the object can be assigned to a reference. That means you get a chance to step in and do things to get the object ready for use. In other words, before anyone can use the remote control for an object, the object has a chance to help contruct itself. In our Duck constructor, were not doing anything useful, but it still demonstrates the sequence of events.
说白了,constructor就像一个method,只不过跟这个class的名字一样,而且有()在后面,比如public class Duck {}, 它的constructor就是 public Duck() {}。 但是,constructor没有return type,method有,这也是你如何分辨constructor和method。

Overloaded constructor

Overloaded constructors means you have more than one constructor in your class.
To compile, each constructor must have a different argument list!

Bullet points

上一篇 下一篇

猜你喜欢

热点阅读