动手动脑--类与对象

1.继承条件下的构造方法调用

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();  
  }
}

通过 super 调用基类构造方法,必须是子类构造方法中的第一个语句。

2.子类父类拥有同名时

package o;
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);
	}
}

当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定,这就是说:对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。

3.接口

定义一个接口,采用关键字interface,实现一个接口,采用关键字implements 接口的成员函数自动成为public的,数据成员自动成为 static和final的。 如果接口不声明为public的,则自动变为package。 一个类可以同时实现多个接口。

IFood f = new Duck();    接口类型 接口类型的变量=new 实现了接口的具体类型();

posted on 2019-10-23 21:00  帝星辰  阅读(156)  评论(0编辑  收藏  举报

导航