1, hands-on labs
Source
class Grandparent
{
public Grandparent()
{
}
public Grandparent(String string)
{
}
{
public Parent()
{
// super("Hello.Grandparent.");
{
public Child()
{
System.out.println("Child Created");
{
public static void main(String args[])
{
}
Parent Created
Child Created
2, thinking
Why constructor in subclass before you run, you must use the constructor of the parent class? Can you turn? why?
Constructor is used to initialize a variable, the variable subclass inherits the parent class, if you do not call the parent class constructor, some of uninitialized variables.
If the sub-class constructor call first, not the parent class and subclass variable will result in an error
3、
class A{
}
public class part1 {
public static void main(String[] args){
System.out.println(new A());
}
}
Operating results as follows:
exercise.A@15db9742
When calling a constructor initializes the object class, the object return output hash value, and, in hexadecimal notation.
4、
class Father
{
public void show()
{
System.out.println("父类");
}
}
class Son extends Father
{
public void show()
{
super.show();
System.out.println("子类");
}
}
public class test2
{
public static void main(String[] args)
{
Son s=new Son();
s.show();
}
}
Results:
parent
Subclass
5、
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);
}
}
1. What result of the program is left?
2. Explain how you will get this output?
3. The computer is not wrong, why get this result is also a reason to run, then run from these results, you can summarize what syntax features of Java?
result
When the object is assigned to the sub-class parent class object, method call parent class object method all subclasses, parent.myValue ++ changed value is simply the value of the parent class myValue this case, the result is still the subclasses 200 is myValue value, and ((child) parent) .myValue ++ is changed myValue subclass values, the output of 201.