动手动脑--类与对象

怎甘沉沦 提交于 2019-12-02 03:27:36

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 实现了接口的具体类型();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!