[Study notes] "Java programming ideas" 8 to Chapter 11

Chapter VIII polymorphism

  1. Multi-state conditions:

    1. have inherited

    2. The parent object references subclass object

    3. The method must be rewritten

  2. Polymorphic effects: the elimination of the coupling between the types.
  3. A method call is associated with a method body referred to collectively as binding . If prior to program execution bindings, called early binding; at runtime based on the type of object binding, called late binding, also known as dynamic binding, runtime binding.
  4. In addition to static methods in Java and final method, all other methods are late binding. So the final effect also closed dynamic binding.
  5. Only non-private methods can be covered, but also need to pay close attention to the phenomenon of private coverage method, then although the compiler does not complain, but it will not perform in accordance with our expectations.
  6. If a child object to depend on other objects, and initialization sequence should be destroyed in reverse order.
  7. Polymorphic region is not only an ordinary method calls are polymorphic. If direct access to a domain, this visit will be resolved at compile time, that domain is a static resolution of. Static methods are not polymorphic .

Chapter IX Interface

  1. Abstract methods and classes:

    abstract method is incomplete, only the statement without method body comprising an abstract class method called abstract class; if a class contains one or more abstract methods, must be defined as an abstract class of if from an abstract class inheritance, and want to create objects of the class, then it must provide method definitions for all the abstract methods in the base class; if you do not, then the derived class is an abstract class, and the compiler will force us to use the abstract keyword to limit the class.
    abstract void f();


  2. interface keyword produces a completely abstract class, it did not provide any specific implementation

    To make a class to follow a particular interface (or group of interfaces), you need to use the implements keyword

  3. If the interface from a class of non-inherited, you can only inherit from one class; you can inherit multiple interfaces
  4. Interface can be extended multiple-inheritance interfaces, interfaces can also be nested.
  5. Interface is the way to achieve multiple inheritance, while the typical way an object's interface is generated to follow the factory method. On the factory object it is to create a method call, and the factory object to be created, an implementation of the interface.
  6. Domain may comprise an interface, and is implicitly static and  finalthe.
  7. Interface keyword interfacebefore you can add publica modifier, without default packet access method is the default interface publicis.

Chapter X inner class

  1. Will be placed inside a class definition defines another class, which is an internal class.
  2. Creating objects inside a class from any location other than the non-static method of the outer class, you must specify the type of OuterClassName.InnerClassName this particular object.
  3. The ordinary non-static inner classes automatically have access (including private) of all members of its enclosing class

  4. If you need to generate an external class object reference, you can use the name behind the outer class followed .this
    public class DotThis {
        void f() {
    	System.out.println("DotThis.f()");
        }
        public class Inner {
    	public DotThis outer() {
    	    return DotThis.this;//通过.this返回外部类对象
    	}
        }
        public Inner inner() {return new Inner();}
        public static void main(String[] args) {
    	DotThis dotThis = new DotThis();
    	DotThis.Inner dtInner = dotThis.inner();
    	dtInner.outer().f();
        }
    }
    

    If you want to create an internal class object, you must use an external class object and .new

    public class DotNew {
        public class Inner {}
        public static void main(String[] args) {
            DotNew dn = new DotNew();
            DotNew.Inner dni = dn.new Inner();
        }
    }
    
  5. If you have a specific abstract class or category rather than the interface, then it can only be used inside the class implements multiple inheritance
    public class Example1 {
        public String getName() {
            return "llb";
        }
    }
    public class Example2 {
        public int getAge() {
            return 25;
        }
    }
    
    public class MultiImplementation {
        private class test1 extends Example1 {
            public String getName() {
                return super.getName();
            }
        }
        private class test2 extends Example2 {
            public int getAge() {
                return super.getAge();
            }
        }
        public String getName() {
            return new test1.getName();
        }
        public int getAge() {
            return new test2.getAge();
        }
    
        public static void main(String[] args) {
            MultiImplementation my = new MultiImplementation();
            System.out.println("姓名: " + my.getName());
            System.out.println("年龄: " + my.getAge());
        }
    }
    
  6. It refers to the internal local inner classes in the class definition in the process or action

      • Internal classes can not have local access specifiers
      • Partial internal access to all current members of the class as well as constants within this class peripheral block

     Partial inner classes will follow with other classes compile, but the scope of the definition of the method or partially within the class outside the local inner class is unavailable

  7. Inner class declared staticwhen, no longer contains a reference to the periphery of the object .this, called a nested class (and C ++ nested classes were similar, but those who can not access private members of the class in C ++, and can be accessed in Java).
    - create a nested class, no external object.
    - can not access non-static peripheral object from a nested class.
    public class OuterClass {
        private static String address = "Shanghai";
        public static class StaticInnerClass {
            public String getAddress() {
    	    return address;
    	}
        }
        public static void main(String[] args) {
    	OuterClass.StaticInnerClass sic = new  
                                         OuterClass.StaticInnerClass();
    	String address = sic.getAddress();
    	System.out.println(address);
        }
    }
    
  8. Anonymous inner class created way:

    new 外部类构造器(参数列表)或接口 {}
    1. While the definition of the class generates an instance of the class interior, then the class definition will disappear, so anonymous inner classes can not be reused
    2. Anonymous inner class must inherit from a parent class or implement an interface, but can only inherit from a parent class or implement an interface
    3. Anonymous inner classes can not define constructors (no class name), any static member variables and static methods can not exist
    4. Anonymous inner classes can not be abstract, its interface all the abstract methods must implement the inherited class or
    public interface Contents {
        int value();
    }
    public class Parcel7 {
        public Contents contents() {
            return new Contents() {
                private int i = 1;
                public int value() { return i; }
            };
        }
    
        //等价于
    /*
        class MyContents implements Contents {
            private int i = 1;
            public int value() { return i; }
        }
        public Contents contents() { return new MyContents(); }
    */
    
        public static void main(String[] args) {
            Parcel7 parcel7 = new Parcel7();
            Contents c = parcel7.contents();
        }
    }

    When anonymous inner classes to pass parameters, if the parameter is used within the class, then the parameter must be declared final

    Parcel9 class {public 
        // dest object is defined externally, it must be defined as a final parameter references 
        public Where do you want the Destination (final String dest) { 
    	return new new the Destination () { 
    	    Private String label = dest; 
    	    @Override 
    	    public String readLabel ( ) { 
                    return label; 
    	    } 
    	}; 
        } 
        public static void main (String [] args) { 
    	Parcel9 parcel9 new new Parcel9 = (); 
    	the Destination Where do you want = parcel9.destination ( "of Shanghai"); 
    	System.out.println (destination.readLabel ( )); 
        } 
    }
  9. Why if the final? Inner class is not directly call the method parameters passed, but to use its constructor parameters passed to back up their own internal parameters of the method call is actually their own property rather than an external method passed in, in the inner class both the properties and parameters of external methods appears to be the same thing, but in fact is not, that does not affect the changes of this nature to the outside parameter within the class, if the property changes inside the class , while the external process parameter has not changed, it is difficult to accept, in order to ensure the consistency of the parameters, to a predetermined final use of both is not changed to avoid simultaneous.
  10. Each class will have a .class file, which contains all the information on how to create an object of that type; inner classes must also be generated to have a .class file to include their class object information, which is naming rules:

    Enclosing class name, add "$", plus the name of the inner class, if anonymous inner class, the compiler will simply generate a number as its identifier, such as:

    Outer$Inner.class
    Outer$1.class

Chapter XI hold objects

  1. Collection is a collection of interfaces, the method provides a common interface for the collection of objects operating
    Collections wrapper class is a static method comprises various set of operations, such can not be instantiated, as a tool type, the frame serving Collection
    Collection basic interface is a collection of interfaces, a collection represents a group of Object, i.e. elements collection
  2. List, Set, Queue interfaces are implementation of the interface Collection

    • List: Save the elements must be inserted in the order
    • Set: you can not have repeated elements
    • Queue: Queue accordance with the rules to determine the order of the objects is generated (usually the same order of insertion elements)
  3. Arrays Collections class and there are many practical method Java.util package, a set of elements may be added in the Collection; Arrays.asList () method takes an array or list of elements divided by a comma (using a variable parameter ), and converts it to a list object; Collections.addAll () method takes a Collection object, and an array or by a comma-separated list, to add elements to the Collection
    import java.util.*;
    
    public class AddingGroups {
        public static void main(String[] args) {
    	Collection<Integer> collection = 
    	    new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
    	Integer[] moreInts = {6, 7, 8, 9, 10};
    	collection.addAll(Arrays.asList(moreInts));//更快,但不够灵活
    	Collections.addAll(collection, 11, 12, 13, 14, 15);
    	Collections.addAll(collection, moreInts);//更加灵活
    	List<Integer> list = Arrays.asList(16, 17, 18, 19, 20);
    	list.set(1, 99);
        }
    }
  4. Arrays like Collections, is a utility class

    Arrays.asList () returns a fixed-size list supported by the specified array can be used to convert the array into a List

    In turn, using the List toArray () method, it can be converted into an array List

  5. Print containers

    Must use of Arrays.toString () array to produce a printable representation

  6. List

    ArrayList: random access, but is slow in the middle of the insertion or removal of elements of List

    LinkedList: insertion and deletion operations performed by the middle and at lower cost List, a sequential access optimization; slow random access

    ArrayList common method

    contains (Object o): determining whether an object in the list

    remove (int index): Removes the element at the specified position

    indexOf (Object o): Returns the index of the specified element in the list the first time, if the element is not included, -1

    add (E e): Add the tail of this list-making element

    add (int index, E e): the specified element is inserted into the specified position

  7. Iterator is an object that is to work through and select an object in the sequence

    The Java Iterator only one-way move can only be used:

    1. The first element is ready Iterator return sequence; use iterator () Returns an Iterator claim container
    2. Use next () to get the next element in the sequence
    3. Use hasNext () to check whether there are elements of the sequence
    4. Use remove () will return the iterator element of the newly deleted
  8. LinkedList common method

    addFirst (E e) / addLast (E e): add an element to the beginning of the list / end

    getFirst () / element (): Returns the first element of the list

    peek () / peekFirst (): Retrieves, but does not remove, the first element of the list

    offer (E e) / offerLast (E e): the element is inserted into the end of the list

  9. Queue

    A typical queue first in first out order (FIFO) container, i.e. from one end of the container into things, taken from the other end of things into the container and removed with the same sequence

    LinkedList is provided a method to support the behavior of the queue, and it implements the Queue interface, LinkedList thus may be used as an implementation of Queue, it may be upcast Queue LinkedList

  10. Set

    Set does not save duplicate elements; Set most commonly used test attribution, we can easily ask if an object is in a Set of

    Storage element method:

    HashSet: using a hash function

    LinkedHashSet: hash, but it looks like using a linked list to maintain the element insertion order

    TreeSet: The elements stored in Red - Black tree structure

  11. Map: a composition on the "key to" objects, allowing the use of keys to find value; mapping table allows us to use another object to find an object, it is called "associative arrays" because it objects to some Other related objects together, otherwise known as "dictionary"

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();

    More complex forms

    Map<Integer, List<String>> map = new HashMap<Integer, List<String>>(); map.put(1, rrays.asList("lv", "long", "bao"));

    The key is a map Set, value is a Collection

    Map common method

    get (Object o): Returns the value of the specified key is mapped, if the mapping does not contain this key, return null

    put (K key, V value): the specified value associated with the specified key in this map, if the mapping relation already exists, an updated value

    hashCode (): Returns the hash code value for this map

    Three kinds of Map implementation

    HashMap: Based on the hash table "zipper" method to generally used in a single thread, not thread safe

    HashTable: Based on the hash table "zipper" method to generally used in multiple threads, thread-safe

    TreeMap: ordered hash table, achieved by red-black tree, generally used for storing an ordered mapping of a single thread

  12. to sum up:
    1. And an array of digital objects linked: it saves clear type of the object, the object query, the results do not need to type conversion; it can be multi-dimensional, you can save the basic types of data; however, once the array is generated, its capacity can not be changed
    2. Collection saved single element, and save the Map associated key-value pairs: With Java generics, you can specify the type of objects stored in the container, so the object you will not be placed into the wrong type of container, and from when the container to obtain elements do not have to type conversion; various and Map Collection can be when you add more elements to which automatically adjusts its size; basic types of containers can not hold, but the automatic packaging mechanism will perform basic carefully type to a container held between the wrapper installed bidirectional type transducer
    3. Like an array, List also associated with the object index numbers, therefore, arrays and List are sorted container; List can automatically expand capacity
    4. If you want a lot of random access, use ArrayList; if you often insert or remove elements from the middle of the table, you should use LinkedList
    5. Queue and stack of various acts, supported by LinkedList
    6. Map is a design object (not numbers) associated with the object: HashMap designed for quick access; holding the TreeMap "key" is always ordered state, there is no fast HashMap; a LinkedHashMap holding element into the sequence, but also by hash provides fast access capability
    7. Set does not accept duplicate elements: HashSet provides the fastest search speed; TreeSet to keep the elements in sorted state; LinkedHashSet stored in order to insert elements
    8. The new program should not use outdated Vector, Hashtable, and Stack (Reference reasons: https://www.cnblogs.com/fudashi/p/7214609.html )

Guess you like

Origin www.cnblogs.com/mcq1999/p/12083193.html
Recommended