Java job 04 classes and objects

Source: Internet
Author: User
Tags instance method

I. Hands-on brain

1) Title: Verify Classandobjecttest.java (Use custom Class)

2) Source code:

public class Classandobjecttest {public    static void Main (string[] args) {        //creates an instance of the class, defines an instance of an object variable reference        MyClass obj = new MyClass ();        Call the class's public method        Obj.mymethod ("Hello") through the object variable;        Assigning a value to a property        Obj.setvalue (+);        The current value of the output attribute        System.out.println (Obj.getvalue ());        Direct access to the Object public field        obj.information = "Information";        The current value of the public field of the output object        System.out.println (obj.information);}    } /** * Example of a custom Java class */class MyClass {    //public field common    String information = "";    Custom public Java instance method publicly    void MyMethod (String argu) {        System.out.println (ARGU);    } Define Properties: Private field +get method +set method    private int value;    public int GetValue () {        return value;    }    public void SetValue (int value) {        this.value = value;    }}

3) Experimental results:

4) Experimental analysis: from the result, we need to define an object variable, and then "Create (New)" An object, assign the value to the object variable.

Two. Problem solving

In the early days we often defined variables "int value=100;", whereas the previous example defined the variable "MyClass obj=new MyClass ();", are the variables defined in these two ways the same?

Not the same.

The former is "primitive data type", such as int,float variables;

The latter is a reference type variable, and the variable referring to an object is called a variable of reference type, sometimes referred to as an object variable.

In terms of variables and memory allocations, when declaring a variable of an object type, there is actually no object created, and this variable is =null. When a variable of the original type is defined, it is allocated memory immediately.
From the initialization of a variable, Java requires that the variable be explicitly initialized when the original variable is defined, and the initialization of the object variable: If the object variable does not reference a real object, it must be declared null.
and object variables after referencing the object, and if this variable is no longer used, the JVM reclaims the memory (garbage collection) that the MyClass object consumes.

Three Problem solving

For variables of the original data type (such as int), you can use "= =" to determine whether two variable values are equal, then the object variable can also use "= =" to determine whether two variable values are equal?

Verify Related programs:

public class Test {public    static void Main (string[] args) {        //TODO auto-generated method Stubfoo obj1 = new Foo ( ); Foo obj2 = new Foo (); System.out.println (OBJ1==OBJ2);    }} Class foo{    int value=100;}

Operation Result:

Conclusion: It is not possible, similar to the comparison size of a string, to use Equals () for comparison with the same usage.

Attention:

When "= =" is applied to the "raw data type" variable, is the data saved by the comparison variable equal
When "= =" is applied to a "reference type" variable, it is compared whether the two variables refer to the same object.
The reference represents the address, so "= =" is actually equivalent to comparing the address of an object saved in two reference type variables.

So, the correct code is as follows:

public class ObjectEquals {
public static void Main (string[] args) { mytestclass obj1=new mytestclass (+); Mytestclass obj2=new Mytestclass (+); System.out.println (OBJ1==OBJ2); System.out.println (Obj1.equals (OBJ2));} } Class mytestclass{public int Value; Note: Only the parameter type is object, the Equals method //parameter type that overrides object is Mytestclass, and only the Equals method is overload. // @Override //Public Boolean equals (Object obj) // { // return (( (mytestclass) obj). Value==this. Value; } public Boolean equals (Mytestclass obj) { return obj. Value==this. Value; } Public mytestclass (int initvalue) { value=initvalue; }}

The results of the operation are as follows:

Four. Problem solving

How do I compare the contents of two objects?

1) The "content" of two objects, in fact, refers to the values of all the fields at a certain point in time, "content equal", in fact, the "corresponding field value" is consistent. In Java, the Equals () method of the base class (override) can be overridden by the value of a field in two objects.

Note: When you define a class, the default is object if you do not explicitly indicate which of its "father" classes it is. object is the topmost base class for Java, which defines the Equals () method.

Override the Equals () method of the base class:

public class ObjectEquals {public    static void Main (string[] args) {                mytestclass obj1=new mytestclass (+);                Mytestclass obj2=new Mytestclass (+);                System.out.println (OBJ1==OBJ2);                System.out.println (Obj1.equals (OBJ2));}    } Class mytestclass{public    int Value;        Note: Only the parameter type is object, the Equals method        //parameter type that overrides object is Mytestclass, and only the Equals method is overload.       @Override public     boolean equals (Object obj)    {return ((mytestclass) obj). Value==this. Value;   }       /* Public    Boolean equals (Mytestclass obj)    {        return obj. Value==this. Value;       } *    /public mytestclass (int initvalue)     {              value=initvalue;    }}

Operation Result:

2) In addition to overriding the Equals method of the base class, we can also "overload (Overload)" The Equals () method:

Note: the Equals () method has a parameter type of Mytestclass instead of an object, and the method itself does not have a "@Override" tag attached to it, compared to the previous "override" Way of code.

public class ObjectEquals {public            static void Main (string[] args) {                mytestclass obj1=new mytestclass (+);                Mytestclass obj2=new Mytestclass (+);                System.out.println (OBJ1==OBJ2);                System.out.println (Obj1.equals (OBJ2));}        } Class mytestclass{public        int Value;        Note: Only the parameter type is object, the Equals method        //parameter type that overrides object is Mytestclass, and only the Equals method is overload. Public       Boolean equals (Mytestclass obj)       {               return obj. Value==this. Value;       }     Public mytestclass (int initvalue)        {                value=initvalue;    }}

Operation Result:

Five. Problem solving

Why is the following code not compiled? Where did it go wrong?

public class Test {public    static void Main (string[] args) {        //TODO auto-generated method stub     Foo obj1 = new Foo ();    }} Class foo{    int value;public Foo (int initvalue) {    value=initvalue;}}

Conclusion: If a class provides a custom construction method, the default construction method is no longer provided by the system. So you can add "foo obj1 = new Foo ();" Change to "foo obj1 = new Foo (4);".

Six. Problem solving

If a class has both an initialization block and a constructor, and it also sets the initial value of the field, who decides?

Such as:

In "public int field = 100;" In "{field=200;}" Before, it was "{field=200;}" In the end, it is "public int field = 100;" Say That is, who is more dependent upon who initializes the function.

Note: The default value specified when executing a class member definition or the initialization block of a class, exactly which one you want to see is "in front". Executes the constructor of the class. The initialization blocks of the class do not receive any arguments, and they are executed whenever an object of the class is created. Therefore, it is appropriate to encapsulate those "code that must be executed when the object is created."

The specific procedures are as follows:

public class Initializeblockdemo {    /**     * @param args     *    /public static void main (string[] args) {                Initializeblockclass obj=new Initializeblockclass ();        System.out.println (Obj.field);                Obj=new Initializeblockclass (+);        System.out.println (Obj.field);    }} Class initializeblockclass{    //The following sentence precedes and after the initialization of the block, which affects the initial value of the field fields public    int field=100;//before    {        field=200;    }    public int field=100;//after public    initializeblockclass (int value) {        this.field=value;    }    Public Initializeblockclass () {       }}

Operation Result:

① "public int field = 100;" In "{field=200;}" Before:

② "public int field = 100;" In "{field=200;}" After:

Seven. Problem solving

Run the Teststaticinitializeblock.java sample, observe the output, and summarize the "Order of execution of static initialization blocks".

Experimental test:

Class root{    static{        System.out.println ("Static initialization block of Root");    }    {        System.out.println ("Root's normal initialization block");    }    Public Root ()    {        System.out.println ("Root parameter-free constructor");}    } Class Mid extends root{    static{        System.out.println ("Static initialization block for Mid");    }    {        System.out.println ("normal initialization block for mid");    }    Public Mid ()    {        System.out.println ("parameter-free constructor for mid");    }    Public Mid (String msg)    {        //The constructor that is overloaded in the same class is called through this        ();        System.out.println ("Mid with parametric constructor, whose parameter value:" + msg);}    } Class Leaf extends mid{    static{        System.out.println ("Static initialization block of the Leaf");    }    {        System.out.println ("normal initialization block of the Leaf");    }        Public Leaf ()    {        //        The constructor super ("Java initialization sequence demonstration") that has a string parameter in the parent class is called through Super;        System.out.println ("The constructor that executes the leaf");}    } public class teststaticinitializeblock{public    static void Main (string[] args)     {        new Leaf ();}    }

Operation Result:

Conclusion (static initialization block execution order): Static initialization blocks are executed only once. When you create an object of a subtype, it also causes the execution of the static initialization block of the parent type.

Eight. Problem solving

Static methods only allow access to static data, so how do you access the instance members of a class in a static method (that is, a field or method that does not have the static keyword attached)?

Static methods only allow access to static data, so how to access instance members of a class in a static method (that is, a field or method that does not have a static keyword attached)

public class Text4 {

public static void Main (string[] args) {
TODO auto-generated Method Stub
Static
System.out.println ("(static variable) total_employees =" +employee.clear ());
Instance
Employee E = new Employee ();
System.out.print ("(instance variable) name =" +e.name);
}

}
Class Employee
{
String name = "2";
Long salary;
Short employee_id;
static int total_employees = 0;
static int Clear () {
return total_employees;
}
static void Clear2 () {
}
}

Operation Result:

Java job 04 classes and objects

Related Article

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.