多态:
package com.hou.oop2;
public class Animal {
String name;
public void eat(){
System.out.println("动物在吃东西");
}
public void sleep(){
System.out.println("动物在睡觉好觉");
}
}
package com.hou.oop2;
public class Cat extends Animal{
String color;
public void eat(){
System.out.println("猫在吃");
}
}
package com.hou.oop2;
public class Dog extends Animal {
String kind;//狗的品种
public void eat(){
System.out.println("狗在吃");
}
}
package com.hou.oop2;
public class TestDuoTai {
public static void main(String[] args) {
Animal animal=new Animal();
animal.eat();
Animal animal1=new Dog();
animal1.eat();
System.out.println("-------------------");
/*
*
*
*
* 基本数据类型:byte float double int long
* boolean
* char
*
*
* 引用数据类型:String 数组 类 接口
*
* 向下转型和向上转型
* */
/* int i=3;
float f=i;
System.out.println(i);
//需要加上F或者f
float j=3.4f;
int f1=(int)j;
System.out.println(f1);
*/
//引用数据类型也适用于向下转型和向上转型
//子类,实现类 小类型 父类,接口 大类型
/*Dog dog=new Dog();
Animal animal2=dog;*/
//两者等效
Animal animal3=new Dog();
animal3.eat();
//animal3有两种引用,定义的时候指向的是Animal,赋值的时候指向的是Dog
//使用父类代表子类,执行的是子类重写后的逻辑,表现出子类不一样的状态
//多态
//把动物强转为猫
/* Cat cat=(Cat) animal;
cat.eat();
instance of 判断该类的类型
*/
if(animal instanceof Dog){
Dog d1=(Dog)animal;
System.out.println("该动物是一只狗");
}else {
System.out.println("强制转换错误");
}
}
}
可以知道多态也是一种向上转型,我们的int,float等等类型也可以进行相关的转换,大的转换为小的可能出现相关的错误,所以需要我们谨慎。
构造器:
package com.hou.constructor;
public class Dog extends Animal {
public Dog(){
System.out.println("dog的无参构造方法");
}
}
package com.hou.constructor;
public class Animal {
String name;
public Animal(){
System.out.println("Animal的无参构造方法");
}
public Animal(String name){
this.name=name;//可以进行赋值
System.out.println("执行了有参的构造方法");
}
}
package com.hou.test;
import com.hou.constructor.Animal;
import com.hou.constructor.Dog;
public class TestAnimal {
public static void main(String[] args) {
Animal animal=new Animal();
// 构造方法注意事项
// 1. 只不需要new以后就可以自己编译
// 2. 构造方法会默认有一个无参的构造方法,但是如果有一个有参的构造方法会没有无参的构造方法,需要重新定义
//
// java是单继承,比如Dog只可以继承一个类Animal就不可以继承其他的类了
//
// 因为dog继承了Animal所以会执行An
// imal和dog的构造方法
Dog dog=new Dog();
}
}
注意里面写上 的相关注释,包含大部分的知识点。