package com.niu.demo;
public class Extends_{
public static void main(String[] args){
Manager niu = new Manager("Niu",18);
System.out.println(niu.toString());
//父类多态引用子类
Employee zhang = new Manager("zhang",20);
Employee li = new Employee("li",17);
niu.doWork();
zhang.doWork();
li.doWork();
//instanceof测试对象是否相同或者有继承关系
System.out.println(niu instanceof Employee);
System.out.println(niu instanceof Manager);
System.out.println(li instanceof Manager);
}
}
//继承Employee类,私有方法之外的方法将会自动继承
class Manager extends Employee{
public Manager(String name,int age){
//调用父类构造
super(name,age);
}
//重写父类方法
public void doWork(){
System.out.println("Manager is work!");
}
}
class Employee{
private String Name;
private int Age;
//静态与常量
private static int count = 0;
private final static String sex = "man";
//实例化块,不是必须的
{
//this.Name = "default";
}
//默认构造
public Employee(){
this.Name = "default";
this.Age = 0;
}
//带参构造
public Employee(String name,int age){
//构造器调用构造器
//this()
this.Name = name;
this.Age = age;
this.count++;
}
//访问器方法
public String getName(){
return this.Name;
}
public int getAge(){
return this.Age;
}
//修改器方法
public void setName(String name){
this.Name = name;
}
//静态方法只能访问静态成员
public static int getCount(){
return count;
}
public void doWork(){
System.out.println("Employee is work");
}
//重写Object的方法
public String toString(){
return "name: "+this.Name+" age: "+this.Age;
}
//重载toString方法
public String toString(int age){
return "name: "+this.Name+" age: "+age;
}
}