Seventh day of basic Java learning-object-oriented common concepts

Source: Internet
Author: User

Document Version Development Tools Test Platform Project Name Date author Notes
V1.0 2016.02.26 Lutianfei None
member variables and local variables
    • 成员变量With the 局部变量 difference:
      • A: The position in the class is different
        • Member variables: In a class, outside of a method
        • Local variables: In a method definition or on a method declaration .
      • B: The location in memory is different:
        • Member variable: in heap memory
        • Local variables: In stack memory
      • C: Different life cycle
        • Member variables: As objects are created, they disappear as the object disappears
        • Local variables: As a method is called, it exists as the method is called
      • D: Different initialization values
        • Member variable: has default initial value
        • Local variables: There is no default initial value , which must be defined and assigned before it can be used.
    • Note: The local variable name can be the same as the member variable name, which is used when 就近原则 using in the method.
formal parameter problems for class types
    • The formal parameter of a method is a class, which in 类型(引用类型) fact requires the object of the class .
//Formal parameters are basic typesClass Demo { Public int sum(intAintb) {returnA + b; }}//Formal parameter is a reference typeClass Student { Public void Show() {System.out.println ("I love learning."); }}class Studentdemo {//If you see a method in which the formal parameter is a class type (reference type), the object of the class is actually required.      Public void Method(Student s) {//Call, the address of s in the main method is passed here Student s = new Student ();S.show (); }}class Argstest { Public Static void Main(string[] args) {//formal parameter is a basic type of callDemo d =NewDemo ();intresult = D.sum (Ten, -); System.out.println ("Result:"+result); System.out.println ("--------------");//Formal parameter is a call to a reference type        //demand: I want to call the method () methods in the Studentdemo classStudentdemo SD =NewStudentdemo ();//Create student ObjectsStudent s =NewStudent (); Sd.method (s);//Give the address of S to here}}


Anonymous Objects
    • Anonymous object: Is an object without a name . is a simplified representation of an object.
    • Two use cases for anonymous objects
      • Object Call method only once
      • Pass as actual parameter
    • Anonymous invocation Benefits
      • The anonymous object call is complete garbage. Can be reclaimed by the garbage collector.
Class Student { Public void Show() {System.out.println ("I love learning."); }}class Studentdemo { Public void Method(Student s)    {s.show (); }}class Nonamedemo { Public Static void Main(string[] args) {//Call with a nameStudent s =NewStudent ();        S.show ();        S.show (); System.out.println ("--------------");//Anonymous object        //new Student ();        //Anonymous object invocation method        NewStudent (). Show ();NewStudent (). Show ();//This is actually re-created a new objectSystem.out.println ("--------------");//Anonymous object passed as actual parameterStudentdemo SD =NewStudentdemo ();//Anonymous objectSd.method (NewStudent ());//One more        NewStudentdemo (). Method (NewStudent ()); }}


Package
    • Package Overview:

      • Refers to the properties and implementation Details of hidden objects, and provides public access only to the outside.
    • Benefits:

      • Hide implementation details and provide public access
      • Improved reusability of the Code
      • Improve Security
    • Encapsulation principle:

      • Hide content that you don't need to provide externally.
      • Hides the property and provides a public way to access it.
    • Note:

      • The test class typically creates only objects, calling methods.
Private keyword
    • is a permission modifier , which is an embodiment of encapsulation.
    • Members can be decorated ( member variables and member methods )
    • Members that are modified by private are only accessible in this class .
the most common application of private
    • Modify the member variable with private
    • provides the corresponding getxxx ()/setxxx () method
This keyword
    • this: Represents an object reference for the same class
    • Method is 对象 called, this represents the object
Class Student {//Name    PrivateString name;//Age    Private intAge//Name Get value     PublicStringGetName() {returnName }//Name setting value     Public void SetName(String name) {//name = "Brigitte";        //student.name = name;         This. name = name; }//Age gain value     Public int Getage() {returnAge }//Age Assignment     Public void Setage(intAge) { This. Age = Age; }}//Test classClass Studenttest { Public Static void Main(string[] args) {//Create student ObjectsStudent s =NewStudent ();//Assign a value to a member variableS.setname ("Brigitte"); S.setage ( -);//Get DataSystem.out.println (S.getname () +"---"+s.getage ()); }}


Construction Method
    • Overview of construction method functions

      • initializing data to an object
    • Structuring method formats

      • The method name is the same as the class name
      • No return value type, not even void
      • There is no specific return value. (Can have return; This statement means that the method ends here.)
    • Construction Method Considerations

      • If you do not provide a constructor method, the system will give the default parameterless construction method
      • If you provide a construction method, the default parameterless construction method will no longer be provided by the system. Must be given out on their own. (It is recommended that you always give the method of non-parametric construction!) )
      • The construction method can also be overloaded
Class Student {PrivateString name;Private intAge Public Student() {System.out.println ("This is a non-parametric construction method"); }//overloaded format for constructor methods     Public Student(String name) {System.out.println ("This is a construction method with a string type."); This. name = name; } Public Student(intAge) {System.out.println ("This is a construction method with an int type."); This. Age = Age; } Public Student(String name,intAge) {System.out.println ("This is a construction method with multiple parameters"); This. name = name; This. Age = Age; } Public void Show() {System.out.println (name+"---"+age); }}class ConstructDemo2 { Public Static void Main(string[] args) {//Create ObjectsStudent s =NewStudent ();        S.show (); System.out.println ("-------------");//Create object 2Student s2 =NewStudent ("Brigitte");        S2.show (); System.out.println ("-------------");//Create object 3Student s3 =NewStudent ( -);        S3.show (); System.out.println ("-------------");//Create object 4Student S4 =NewStudent ("Brigitte", -);    S4.show (); }}


Standard code notation for a basic class
    • Member variables
    • Construction method
      • Non-parametric construction method
      • Construction method with parameters
    • Member Methods

      • GetXxx ()
      • Setxxx ()
    • How to assign a value to a member variable

      • Non-parametric construction method +setxxx ()
      • Construction method with parameters
/ * A final version of the standard Code.            Student class: member Variable: Name,age construction method: No parameter, with two parameter member method: GetXxx ()/setxxx () Show (): Outputs all member variable values for the class assign a value to the member variable: a:setxxx () method B: Constructs a method to output member variable values: A: by GetXXX () respectively, and then splicing B: by adjusting Use the show () method to fix */Class Student {//Name    PrivateString name;//Age    Private intAge//Construction method     Public Student() {    } Public Student(String name,intAge) { This. name = name; This. Age = Age; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; }//Output all member variable values     Public void Show() {System.out.println (name+"---"+age); }}//Test classClass Studenttest { Public Static void Main(string[] args) {//Mode 1 assigns a value to a member variable        //non-parametric construction +setxxx ()Student S1 =NewStudent (); S1.setname ("Brigitte"); S1.setage ( -);//Output valueSystem.out.println (S1.getname () +"---"+s1.getage ());        S1.show (); System.out.println ("----------------------------");//Mode 2 assigns a value to a member variableStudent s2 =NewStudent ("Elina", -); System.out.println (S2.getname () +"---"+s2.getage ());    S2.show (); }}


Student s = new Student (); What's going on in memory
    • Loading Student.class files into memory
    • In- stack memory for s space-opening
    • In heap memory as a 学生对象 space to open up
    • Default initialization of member variables for student objects
    • Display initialization of member variables for student objects
    • assigning values to member variables of student objects by constructing methods
    • Student object initialization is complete, assign object address to s variable


Static keyword(Heavy difficulty)
    • You can modify member variables and member methods

    • staticKeyword features

      • Load as the class loads
      • precedence over the existence of objects
      • Shared by all objects of the class
        • This is also the condition that we determine whether to use static keywords
      • Can be called through the class name or by an object .
    • staticKeyword considerations

      • The 静态方法 this keyword is not available in ( cannot reference non-static variable xxx from static context )
        • Because static is loaded as the class loads, this it exists as the object is created.
        • Static than object exists first.
      • 静态方法Only static 成员变量 and static 成员方法 , non-static methods can be accessed freely .

Class Teacher { Public intnum =Ten; Public Static intnum2 = -; Public void Show() {System.out.println (num);//implied to tell you that access is a member variableSystem.out.println ( This. num);//explicitly tell you that access is a member variableSystem.out.println (NUM2); } Public Static void Method() {//cannot reference non-static variable num from static context        //system.out.println (num);System.out.println (NUM2);//cannot refer to non-static method function () from a static context        //function ();Function2 (); } Public void function() {    } Public Static void function2() {}}class Teacherdemo { Public Static void Main(string[] args) {//Create ObjectsTeacher T =NewTeacher ();        T.show (); System.out.println ("------------");    T.method (); }}


Static VariablesAnd member VariablesThe difference
    • belong to different
      • static variables belong to classes , so they are also called class variables
      • member variables belong to an object , so also known as instance variables ( object variables )
    • Different locations in memory
      • Static variables stored in the static area of the method area
      • Member variables stored in heap memory
    • Memory occurrence time is different
      • Static variables are loaded as the class is loaded and disappear as the class disappears
      • Member variables exist as the object is created and disappear as the object disappears
    • Call Different
      • A static variable can be called by a class name , or it can be called by an object
      • Member variables can only be called by object name
The Main method is static
    • Public static void Main (string[] args) {}
      • Public, access is the largest, because it is called by the JVM, need access permission is large enough.
      • Static statically, no need to create object, called by JVM, without creating object, direct class name access
      • Void is called by the JVM and does not need to return a value to the JVM
      • Main a generic name, although not a keyword, but is recognized by the JVM
      • String[] args was previously used to receive keyboard input
        • Eg:java Maindemo Hello World Java

Seventh day of basic Java learning-object-oriented common concepts

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.