家蛙”笔记(一) (转载于itpub)

1. Object vs . Class



    
object is instance of class.   object may hold a state which can be

    manipulated at run time
.



    class
is object template .   Class is used to create objects and specify

    their behaviors
.



    class
is an object too ; they are instance of 'Class' class when loaded by

    VM
.



2. Message vs . Method



    Message is a way
for object to provide service to its user .

    
The user request service from an object through sending a message ( properly

    signatured
) to that object .      



    
A Method is a set of instructions to manipulate an object . Accessible

    Methods specify how a message
( with the same signature ) should be handled

    by an object
. Accessible method can be invoked by a message to an object .



3. Static(class) variable vs . Instance variable vs . static(class) method



    Every variables must be typed
( primitive or not );

    

    Static(class)
variables : are common to all objects ( instances ) of the same

                             
class. Static(class) variable is initialized when

                             
class is loaded .

                             
Memory allocated on Heap .

                              

    
Instance variables :       are unique to each object created by a particular

                             
class. Instance variable is initialized during

                             
class instantiation .

                             
Memory allocated on Heap .

                             

    
Local Variables :          Declared   1. Inside a block statement ;

                                        
2. As a method parameter ;

                                        
3. Inside For- Loop ;

                                        
4. On a try {} catch statement

                             Memory allocated on stack
.

                             

                             
Never initialized by default;                                    



    Static(class)
method :

                             
a . Invocation :  

                         

                                
Can be invoked by prefixing it with class name

                                
(or instance name ) and dot notation ( no dynamic

                                binding
, polymorphism does not apply );



                                
Not invoked as a message to an object since no

                                object may
exit at the time ;



                                
No need for object creation or instantiation ;



                             
b . Restriction :    

                            

                                
Can 't access instance variables;



                                Can'
t use 'this' , 'super'





4. Private , Protected , Public , Package members ( are called Member access

   modifier
)



    
Private :      Accessible only from methods of the host class. Private method

                 is consided not to be inherited at all
;



    
Public :       Accessible by any object ;



    
Protected :    Accessible from methods of the host class and its Subclass

                 
( children , grandchildren ).   Member is private to all outsiders .



    
Package ( omitted ): Accessible to all classes that belong to the same

                 package
, but not to subclass in other packages .



5. Interface



    Definition
:   It is a promise that your class will implement certain methods

                 with certain signatures
; Simply reserve behavior for classes

                 that implement them
;    Marker interface are used to label

                 property of the
class which implements it ;



    
Why :          Are used to augment single inheritance mechanism ; Better

                 solution than aggregation
& forwarding ;



    
Property :     All members in interface are public & abstract ( omitted );

                 
No static methods allowed .



                 
All variables can only be Constants (static & final , omitted );

                 (
There are constants only interface ); No instance field

                 allowed
.



                 
Interface have multi - inheritance , do not have a single

                 top
- level ( root ) interface .



                 
No static method allowed .

                 

                 
A class implements an interface must implement all its methods

                 to avoid abstract feature
.



    
Extend :       Two ways to extend interface : add new methods ; define new

                 
constance ;



    
Interface vs . Abstract class:



                 
Interface are special ( similar ) abstract class that do not

                 define instance variables
( but can define constants ) with

                 all methods be abstract
;  ( SAME )



                 
a . Single vs . multi - inheritance ;

                 
b . All member abstract or not ;  ( DIFFERENCE )



    
Advantage :    Enable multi - inheritance since ( no instance variable ;

                 
Methods only have signatures );   Constant can 't be inherited,

                 but can be used.  



6. Abstract Class



   Definition:    A class labeled as abstract which will prevent any one from

                  instantiating the class;



   Why:           Principle of OO design - to declare common behavior as

                  early as possible in the IS-A hierarchy;  Doing so, some

                  implementation difficult may arise.



   How:           Declare the method as abstract with no body,

                  ex. public abstract float getArea(); Java require us to

                  label the class as abstract.



   Notes:         Subclass abstract or not;



7. OO Program



    A program describe interactions between a collection of objects which are

    designed to model some aspects of the real world.



    Key features of objects: Encapsulation, Inheritance, Polymorphism



8. Bytecode vs. VM



    Platform independent vs. platform dependent.



    Bytecode is generated by compiler,  which is not a machine code (can'
t be

    run by OS directly
), which will be interpreted by VM at run time .



9. Applets



    Small Java applications
and execute in the client 's VM (With Web browser)



10. SecurityManager Objects



    An object that severely restricts applets'
s access to local resource .



11. Java va . HTML



    Java is a stand along program language
, usually has nothing to do

    
with HTML ; HTML was extended to incorporate Java Applets .



12. Programming by Contract



    An way to program which enable the
use of  members ( usually method ) of

    a
class without the need to refer to its implementation details .



13. Mutator vs . Accessor

    

    Report state vs
. modify state of an object .



14. Procedure Call vs . Method Invocation



    Difference
: In addition to the parameters explicitly supplied with a

                message
, a method also has access to the internal state of

                the object
and can manipulate the said state to archive the

                desired result
.



15. Constructor vs . Method



    Naming
:      Constructor must have the same name as the class;



                
Methods usually don 't have the same name as class;

                (But method can have the same name as class)



    Invocation: Constructor is invoked when class is instantiated (new

                operator applied); not as a result of message received.



                Methods are invoked when messages (with the same signature)

                are received by objects;



    Returning:  Constructor has no return type;



                Methods must have return type (void is a return type too);



    Common:     They are usually public (private utility constructor or

                methods);            



                They can be several constructor and same name methods which

                must differ in signature;



                They can call each other;



16. Advantages of Encapsulation



    Enable the creator of class to upgrade, enhance the implementation

    later on.



17. Four Steps of New Operator

    

    a. Allocate memory;

    b. assign default value to instance variables;

    c. invoke the constructor;

    d. Assign object to an identifier (like myCar);



18. CarTest, CarTest.class vs. CarTest.java



    Bytecode, Bytecode vs. Java source code



19. Pointer vs. Class Definition



20. This



    this(); call other constructor.

    this reference to object itself.



21. Final class, method, variable

    

    Final class:    a class that can'
t be parent or can 't be extended (like

                    String);



    Final method:   Methods can'
t be overridden . ( adv . 1. fix certain behavior ;

                    
2. disable dynamic binding )



    
Final variable : Once initialized , their value can 't be changed (you can

                    only assign its value once);

                    

    Blank finals:   Are final variables that are declared and initialized separately.                



22. Common Methods of Object



    toString, equals, clone



23. Three Ways of Entending Class



    a. overriding existing methods;

    b. adding new instance variable;

    c. adding new methods;



24. What is Constructor Chaining



    The ability for subclass'
s constructor automatically invoke

    super
() the first things first ,   in case that your didn 't put

    one there;



25. Override must match signature (in name, number, parameter type and

    access modifier)



26. Package vs. Defaut Package



    Collection of related classes;

    Don'
t need "to create" , come into existence when you declare it .



27. Package Hierarchy vs . Class Hierarchy



    Package has no top
- level , all - encompassing root ;

    
Is a mechanism for creating class library ;   Every class must have at least one

    parents except Objects
.

    

    
adv : ( a ). Seperate different class design ;

         (
b ). Avoid name clash

         
( c ). Information sharing .



28. Full class Name vs . Exception



    Full
class name :     Prefix the class name with its package name and dot

                        notation
.



    
Exception :            

    

        
a . class name immediately following the class keyword ;

        

        
b . class belong to the same package as the class being currently

           defined
;



        
c . class us explicitly specified in one of the import statement .    



        
d . class belong to java . lang package ( which are implicitly imported )



29. Import vs . #include



30. Java .class. path system property



31. str1
== str2 vs .   str1 . equals ( str2 )



    
ex .   str1 = "abcd" ;   str2 = "abcd" .



   TRUE
vs . TRUE . 仅仅字符串特殊,当产生""这种形式时.它是用字符串池中寻找,找到了则赋值,所以==相等



32. class reflection



    Definition
:      The ability to exam classes (list of methods and

                    
constructors ; its super class) from within programs .  

    

    
Why :            class is an instance of Class belongTo java . lang

                    when VM load a
class.

                    

    
Example :         Three method to obtain a reference to Class instance :  

                    
String .class();  

                    Class.
forName ( "abc" );

                    
"abc" . getClass ().



                    
A complex one :

                    Class
c = Color .class();

                    
Field f = c . getField ( txtColor );

                    
Color realColor ( Color ) f . get ( null ); // null for Static

                    

33. Polymorphism



    An object
's ability to decide what method to apply to itself, depending on

    where it is in the inheritance hierarchy, is usually called Polymorphism.



34. Type of object



    Consist its class & all interfaces that it implements.

    

35. Lay Out Manager;

    

    FlowLayout:   default for Applets (Panels)

    

                  Like a word processor; Component can be centered, aligned;

                  Component never resized; Maybe partially displayed or not at all

                  if there is no space left.

    

    BorderLayout: default for Frame (all windows)

    

                  Five regions; Can'
t reserve vertical size and no size for the center .

    

    
CardLayout :

    

    
GridLayout & GridBayLayout ,

    

    
BoxLayout

    

    An example
:

      

      
f . setSize ( 200 , 100 );

                    <-----
f . setLayout (new java . awt . FlowLayout ());

      
MyDrawing d = new MyDrawing ();

      
f . add ( d );

      
d . setSize ( 100 , 50 );   // Ignore or Not

      
f . show ()

      

36. Three way of extending class ( 55 )



    new,
clone , de - serialize

    

37. When will object be destroyed
( 55 )

    

    
a . automatically marked for GC when it is no longer referenced ;

    
b . destroyed for real when VM low on memory ;

    
c . GC runs on separate thread in VM , idle most of the time , and activated when

       VM needs memory
.

    
d . Class itself is not garbage collected .   



    -
Runtime . gc (); Runtime . runFinalization ()   pair

    
- Object finalization .

    

38. Clonable Interface ( 67 )

    

    -
Signature .   protected Object clone () --> public Object clone ()

    -
Why can 't change ' Object ' to something else: clone() is inherited.

    - CloneNotSupportedException



39. Variables (73)



     boolean          true, false         false         1 bit       N/A

     char             Unicode             u0000        16 bits     u0000 - uFFFF

     byte             +-integer           0             8 bits      -128 - 127

     short            +-integer           0             16 bits     -32768 - 32767

     int              +-integer           0             32 bits     

     long             +-integer           0             64 bits     

     float            IEEE 754            0.0f          32 bits

     double           IEEE 754            0.0           64 bits



40. Primitive vs. non primitive type (75)

    

    - Declare: declare a non-primitive type, the memory is not allocated, only a generic

               type;

    - NullPointException: usually mean when a massage was sent to a null reference.



41. Wrapper class (77)



    - Container class (Linked List)

    - Def: Are classes  whose instance is an object representatives of primitive values.

           It can be thought of as classes having single instance variable of

           corresponding primitive type.

    - Wrapper classes are immutable.

    - vs.   Integer i = new Integer(5);  vs.  int i = 5;

         

42. Equality Operators (81)

    

    - == apply to references to objects;

    - s1 = "santa"; s2 = "santa" --> (s1==s2) is true only for String.



43. Array (84)

    - Is objects.

    - Are implicitly created; can'
t be explicitly created ; can 't be extended; Is

      an immediate subclass of Objects; can'
t be extended .

    -
Two way to create array ( three ?)

      *
special initialize syntax   

      
* explicitly supplies the size with new

      *
both    int [] countdown = new int [] { 1 , 2 , 3 }

    -
Once created , length become rvalue .

    -
Y [].class. getSuperclass (). getName () --> Object

    
- Shallow copy vs . System . arraycopy ( stats , 0 , statsCopy , 0 , 4 );

      
arrayCopy has more flexibility .



44. Exception ( 89 )



    -
Def : During execution of your code , certain conditions often occur that usually

           prevent further execution unless something is done to correct the situation
.

           
this condition are commonly called an error or Exception .

    -
Example :   divide by 0 ;   sending msg to null ;  Array index out bound ;

                
reading from closed file ;   method argument out of range .

    -
try {} catch [ finally ] mechanism .    catch like 'switch' , finally will alwas

      executed
.

    -
Exception objects : are used to pass info about exception .

    -
checked vs . unchecked

      must
include in the signature or. not .

    -
Four options we have when invoke a method that declare a checked exception :

      
a . consume it ;

      
b . fishing ( can change message )

      
c . map it ;

      
d . propagate .   

    -
Subclass can ' t throws added exception

     

45. AWT

    - EventHandeler add to Component

    - level 1:  Graphics

      level 2:  Canvas             <--- MouseEvenetHandler

      Level 3.  Panel, window

      level 4:  Applet, Frame      <--- WindowEvenetHandler

    - paint() vs. repaint() [calls update()

      whole pane vs. asynchronous (animation)

    - AWT vs. Swing

      peer vs non-peer;  fast vs. slow; platform dependent or not.



46. Drawbacks on drawing directly on a window

    - virtually impossible to predict the size of the drawable portion of the window.

    - Drawing from scratch and process low-level mouse clickd is a tedious and

      overwhelming programming task.

    - Way out: Component based GUI development.



47. Canvas (105)

    - is not a container

    - it encapsulate a drawing area.

    - size of the drawing area = size of the component

    - no tile bar



48. Four steps to create GUI

    - Create the conponent  (Button bOk = new Button("OK") )

    - add the conponents to a container (container are also conponent)

    - Arrange (layout) the component within their container

    - Handle the event generated by the conponents by registering approperate event

      listner that implements the event handling procedure

      

    - Frame is the only container which have a menu bar:

            MenuBar

               |

               |---- Menu            

               |

               |---- Menu            

               |

               |---- Menu --- MenuItem (setActionCommand("new");

                                        setShortCut(new MenuShortCut(KeyEvent.VK_N)



49. Applets

    - Run application:  Start the VM(interpreter) & suplying a compiled class that

      contains an entry point to the program -- static main() method.

    - Applet is a application that can executed by a web browser as a part of html tag.

      Common methods: - getParameter("text");

                      - size().width;

                      - init, start, paint, stop, destroy

                        

50. Security restriction imposed on untrusted applets;

    - r/w to loacl file system

    - create network connection only to the host of origin (where .class file came)

    - exit java interpreter via. System.exit();

    - spawn new process via. Runtime.exec();

    - open window without warning

    - initiate print job.

    - access system clipboard

    - modify system properties, and read user specific system propertis, such as

      user.home, user.dir



51. De-serialize a file on a web server

    - getDocumentBase()   (.html pape dir)

      getCodeBase()       (.class directory)

    - examle:

       import java.applet.Applet; java.io.*; java.net.*;

       

       class MyApplet extends Applet {

         public void init()

         {

           URL file = null;

           file = new URL(getDocumentBase(), "data/grade.ser");

                 // need catch MalformedURLException.

           ObjectInputStream in = new ObjectInputStream (

                    file.openStream() );

           _grade = (Grade) in.readObject();

         }  

       }  



    - face  = getImage(getDocumentBase(), "img/face.jpg");

      hello = getAudioClip (getDocumentBase(), "snd/hello.au");                            



52. Thread (136)

    - light-weight process running within heavy-weight processes of the OpSys level;

      reduce the overhead; schduling much simple; sharing data (memeroy)

    - create thread must create a class that implements Runnable interface with a single

      method:  void run()

    - t.start();   t.join()

    - thread death shou
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值