java基础――小例子说明封装、继承、多态

时间:2023-02-14 20:10:01

一、继承关系:子类自动拥有父类非私有属性与方法(java只能单继承)

//继承public class OOPTest2
{
public static void main(String[] args)
{
Dog d = new Dog();
System.out.println(d.age);
d.play();
}
}
class Animal
{
protected int age=2;
public void play()
{

System.out.println("animal is playing...");

}
}
class Dog extends Animal
{
//没有写子类的属性与方法
//子类自动拥有父类非私有属性和方法
}

二、接口实现多态:同一个接口的不同实现

//多态public class Test{     public static void main(String[] args)     {         //同一个接口的不同实现         Pet snake =  new Snake();         snake.play();         Pet cat = new Cat();         cat.play();           }}//接口interface Pet{   public void play();}class Snake implements Pet{   public void play()   {      System.out.println("Snake is playing.........");   }}class Cat implements Pet{      public void play()      {         System.out.println("Cat is playing...........");      }}


本文出自 “天涯悬明月” 博客,请务必保留此出处http://brightmoon.blog.51cto.com/8128325/1320506