zoukankan      html  css  js  c++  java
  • 动手动脑类与对象

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

  • 相关阅读:
    BZOJ 1069 最大土地面积
    BZOJ 1059 矩阵游戏
    BZOJ 3570 动物园
    Luogu 3934 Nephren Ruq Insania
    Luogu 3233 [HNOI2014]世界树
    CF613D Kingdom and its Cities
    Luogu 4001 [BJOI2006]狼抓兔子
    Luogu 2824 [HEOI2016/TJOI2016]排序
    POJ 3463 Sightseeing
    Luogu 2495 [SDOI2011]消耗战
  • 原文地址:https://www.cnblogs.com/dixingchen/p/11728867.html
Copyright © 2011-2022 走看看