码迷,mamicode.com
首页 > 其他好文 > 详细

动手动脑--类与对象

时间:2019-10-23 21:48:04      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:类型   imp   rgs   foo   value   system   out   test   parent   

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

动手动脑--类与对象

标签:类型   imp   rgs   foo   value   system   out   test   parent   

原文地址:https://www.cnblogs.com/dixingchen/p/11728867.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!