微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【读书笔记】Core Java for the Impatient 第二章

Object-Oriented Programming

  • Static variables don’t belong to any objects. Static methods are not
    invoked on objects.

  • An inner class is a nonstatic nested class. Its instances have a reference to the object of the enclosing class that constructed it.

  • You can never write a method that updates primitive type parameters.

Default Initialization

Instance variable is automatically set to a default value: numbers to 0,boolean values to false,and object references to null.
In this regard,instance variables are very different from local variables. Recall that
you must always explicitly initialize local variable

Static Variables and Methods

Since static methods don’t operate on objects,you cannot access instance variables from a static method. However,static methods can access the static variables in their class

Packages

It is a good idea to run javac with the -d option. Then the class files are generated in a separate directory,without cluttering up the source tree,and they have the correct subdirectory structure.

A source file can contain multiple classes,but at most one of them can be declared public. If a source file has a public class,its name must match the class name.

nested and Inner Classes

nested Classes

Use a static nested class when the instances of the nested class don’t
need to kNow to which instance of the enclosing class they belong. Use an inner class only
if this information is important.

public class Invoice {
    private static class Item { // Item is nested inside Invoice
        String description;
        int quantity;
        double unitPrice;
        double price() { return quantity * unitPrice; }
    }
    private ArrayList items = new ArrayList<>();
    …
}

There is nothing special about the Item class,except for access control.
If you change the keyword private into public,there is essentially no difference between this Invoice.Item class and a class InvoiceItem declared outside any other class.
nesting the class just makes it obvIoUs that the Item class represents items in an invoice.

Inner Classes

public class Network {
    public class Member {
        …
        public void leave() {
            members.remove(this);
        }
    }
    private ArrayList members;
    …
}

A method of an inner class can access instance variables and methods of its outer class. In this case,they are the instance variables of the outer class object that created it

Comments

//Todo

原文地址:https://www.jb51.cc/wenti/422329.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐