1、
package package1;
class Test
{
private static int x = 10;
public void show(int x)
{
x++;
this.x++;
System.out.println(x+" "+this.x);
}
public static void main(String[] args)
{
int x = 20;
Test t = new Test();
t.show(x);
}
}
【答案】:21 11
2、
package package1;
class Fu{
public int num = 10;
public Fu(){
System.out.println("fu");
}
}
class Zi extends Fu{
public int num = 20;
public Zi(){
System.out.println("zi");
}
public void show(){
int num = 30;
System.out.println(num);
System.out.println(this.num);
System.out.println(super.num);
}
}
class Test {
public static void main(String[] args) {
Zi z = new Zi();
z.show();
}
}
【答案】:
fu
zi
30
20
10
3、
/*
* 1、先加载类 -> 静态代码块中的代码
* 2、构造器 -> 构造代码块+构造方法
*/
class Fu {
static {
System.out.println("静态代码块Fu");
}
{
System.out.println("构造代码块Fu");
}
public Fu() {
System.out.println("构造方法Fu");
}
}
class Zi extends Fu {
static {
System.out.println("静态代码块Zi");
}
{
System.out.println("构造代码块Zi");
}
public Zi() {
System.out.println("构造方法Zi");
}
}
class Test {
public static void main(String[] args) {
Zi z = new Zi();
}
}
【答案】:
静态代码块Fu
静态代码块Zi
构造代码块Fu
构造方法Fu
构造代码块Zi
构造方法Zi
4、
package package1;
/*
* 系统会自上而下寻找构造器,直到找到构造器,并调用构造器
* YXYZ
*/
class X {
Y b = new Y();
X() {
System.out.print("X");
}
}
class Y {
Y() {
System.out.print("Y");
}
}
public class Z extends X {
Y y = new Y();
Z() {
System.out.print("Z");
}
public static void main(String[] args) {
new Z();
}
}
【答案】:YXYZ
5、
package package1;
class Fu
{
public void show()
{
System.out.println("fu show");
}
}
class Zi extends Fu
{
public void show()
{
System.out.println("zi show");
}
public void method()
{
System.out.println("zi method");
}
}
class Test
{
public static void main(String[] args)
{
Fu f = new Zi();
/*
* 子到父,父中没有该方法,所以会报错
*/
//f.method();
/*
* 父到子,将父类的引用转化成子类的引用,前提是子类还是子类
* Zi z = ...;
*/
Zi z = (Zi)f;
z.method();
}
}
【答案】:zi method
6、
package package1;
import java.nio.channels.ShutdownChannelGroupException;
class A
{
public void show()
{
show2();
}
public void show2()
{
System.out.println("我");
}
}
class B extends A
{
// public void show() {
// System.out.println("B");
// }
public void show2()
{
System.out.println("爱");
}
}
class C extends B
{
public void show()
{
super.show();
//System.out.println("C");
}
public void show2()
{
System.out.println("你");
}
}
public class Test
{
public static void main(String[] args)
{
/*
* 1.在执行一个方法(不是构造器)的时候一定先在实例(右边)中找方法,
* 2.找不到,自下而上的找,
* 3.重点,每个方法都要这样去找,执行
*/
A a = new B();
a.show();
B b = new C();
b.show();
}
}
【答案】:
爱
你
7、
package package1;
class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}
class Test{
public static void main(String []args) {
Animal p0 = new Animal();
Dog p1 = new Dog ();
Cat p2 = new Cat ();
Animal p3 = new Dog ();
Animal p4 = new Cat ();
p0 = p1; //向上造型
// p1 = p2; //同类直接不可以直接转化
// p1 = (Dog)p2;
p1 = (Dog)p3; //向下造型
p2 = (Cat)p4;
}
}