Java Chapter III Hands-on brain

Source: Internet
Author: User

public class Initializeblockdemo {

/**

* @param args

*/

public static void Main (string[] args) {

Initializeblockclass obj=new Initializeblockclass ();

System.out.println (Obj.field);

Obj=new Initializeblockclass (300);

System.out.println (Obj.field);

}

}

Class initializeblockclass{

The following sentence affects the initial value of the Field field before and after the initialization block

public int field=100;

{

field=200;

}

public int field=100;

public initializeblockclass (int value) {

This.field=value;

}

Public Initializeblockclass () {

}

}

The result is 100 300; it is obvious that the initialization block of a class in Java will run first only once, and if the variable is assigned a value in the class, it will change the value of the variable, including the Call function assignment.

Package demo;

Public class In extends father{

Public Static void Main (string[] args) {

TODO auto-generated Method stub

In x;

x = new in ();

}

}

class father{

{

int i = 100;

System. out. println (i);

}

}

The result is 100 shows that when there is an inheritance relationship between multiple classes, creating a subclass object causes the parent class to initialize the block's execution

Package demo;

Public class in{

Static int n = 10;

Public Static void Main (string[] args) {

Stac s = new Stac ();

N = S.fuzhi ();

S.Output(n);

}

}

class stac{

int a = 20;

int Fuzhi () {

int x;

x = A;

return x;

}

Static void Output (int b) {

System. out. println (b);

}

}

Result is 20

Using static methods to access instance members of a class is to assign an instance variable of the class to a static variable and then output it with a static method.

Java Chapter III Hands-on brain

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.