第六周Java课后作业

一、p8 动手动脑

1、源代码

package diliuzhou;

class Grandparent
{


public Grandparent()
{

System.out.println("GrandParent Created.");

}


public Grandparent(String string)
{

System.out.println("GrandParent Created.String:" + string);

}

}

 

class Parent extends Grandparent
{


public Parent()
{

//super("Hello.Grandparent.");

System.out.println("Parent Created");

// super("Hello.Grandparent.");

}

}

 

class Child extends Parent
{


public Child()
{

System.out.println("Child Created");

}

}

 

public class TestInherits
{


public static void main(String args[])
{

Child c = new Child();

}

}

2、运行结果

二、p9 思索 为什么子类的构造方法在运行之前,必须调用父类的构造方法?能不能反过来?为什么不能?

子类中,它在调用父类中空参数的构造函数。因为子类继承父类,会继承到父类中的数据,所以必须要看父类是如何对自己的数据进行初始化的。所以子类在进行对象初始化时,先调用父类的构造函数,这就是子类的实例化过程。可以在子类的构造方法中通过super指定调用父类的哪个构造方法。如果没有指定。在实例化子类对象时候会自动调用父类无参的构造方法。然而父类中只有有参的构造方法。

三、、p12

1、源代码

package zy;


public class ExplorationJDKSource {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println(new A());
}

}

class A{}

2、运行结果

四、p19 +号

1、源代码

public class Fruit
{

public String toString()
{
return "Fruit toString.";
}

public static void main(String args[])
{
Fruit f=new Fruit();
System.out.println("f="+f);
// System.out.println("f="+f.toString());
}
}

2、运行结果

五、p28 怎样判断对象是否可以转换

1、源代码

package zy;
public class TestInstanceof
{
public static void main(String[] args)
{
//声明hello时使用Object类,则hello的编译类型是Object,Object是所有类的父类
//但hello变量的实际类型是String
Object hello = "Hello";
//String是Object类的子类,所以返回true。
System.out.println("字符串是否是Object类的实例:" + (hello instanceof Object));
//返回true。
System.out.println("字符串是否是String类的实例:" + (hello instanceof String));
//返回false。
System.out.println("字符串是否是Math类的实例:" + (hello instanceof Math));
//String实现了Comparable接口,所以返回true。
System.out.println("字符串是否是Comparable接口的实例:" + (hello instanceof Comparable));
String a = "Hello";
//String类既不是Math类,也不是Math类的父类,所以下面代码编译无法通过
//System.out.println("字符串是否是Math类的实例:" + (a instanceof Math));
}
}

2、运行结果

六、p30 类型转换

1、源代码

package zy;

public class ParentChildTest {
public static void main(String[] args) {
Parent parent=new Parent();
parent.printValue();
Child child=new Child();
child.printValue();

parent=child;
parent.printValue();

parent.myValue++;
parent.printValue();

((Child)parent).myValue++;
parent.printValue();

}
}

class Parent{
public int myValue=100;
public void printValue() {
System.out.println("Parent.printValue(),myValue="+myValue);
}
}
class Child extends Parent{
public int myValue=200;
public void printValue() {
System.out.println("Child.printValue(),myValue="+myValue);
}
}

2、运行结果

 

posted @   记得关月亮  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示