Class Homework One
Using the class's static fields and constructors, we can track the number of objects created by a class. Write a class that can query it at any time "how many objects have you created?" ”。
Program:
Package com;
public class Duixiang {
public static void Main (string[] args) {
Duixiang a=new Duixiang ();
A.out ();
Duixiang b=new Duixiang ();
B.out ();
}
}
Class duixiang{
static int n=0;
Duixiang () {
n++;
}
public void out () {
System.out.println (" you've created a +n+" Object!) ");
}
}
Results:
Classroom problem Finishing
First, the test:
Operation Result:
Java Field initialization: The variables for all classes are initialized to NULL by default , and the original data type of the numeric class is initialized to 0 by default ,boolean default is initialized to false , initialization blocks and constructors are initialized, and initialization is quickly divided into static initialization blocks and instance initialization blocks. Executes the default value specified by the class member definition or the initialization block of the class, exactly which one you want to see "in front".
Second, the hands of the brain:
When there is an inheritance relationship between multiple classes, creating a subclass object causes the parent class to initialize the execution of the block.
Please write your own sample code to verify the above conclusions.
Program:
Package com;
public class Animal {
public Boolean live=true;
Public String skin= "";
public void Eat () {
System.out.println (" animals need to eat food ");
}
public void Move () {
System.out.println (" Animal movement ");
}
}
Class Bird extends animal{
Public String skin= " feather ";
public void Move () {
System.out.println (" Bird will fly ");
}
}
Class zoo{
public static void Main (string[] args) {
Bird bird=new Bird ();
Bird.eat ();
Bird.move ();
System.out.println ("The Bird has:"+bird.skin);
}
}
:
Third, the hands of the brain:
Run the teststaticinitializeblock.java Sample, observe the output, and summarize the "Order of execution of static initialization blocks".
Results:
The execution order of static initialization blocks:
1. Static initialization blocks are executed only once.
2. When creating objects of subtypes, the execution of static initialization blocks of the parent type is also caused.
Four, an interesting question:
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 methodthat does not have the static keyword attached)?
Please write code to verify your idea.
Program:
Package com;
public class Buttonfactory {
private static Buttonfactory _instance=null;
public static Buttonfactory getinstance () {
if (null==_instance)
_instance=new buttonfactory ();
return _instance;
}
}
Classroom homework and hands-on brain problem finishing