Java面向对象基本特征(2)

示例1:
public class ExtendsDemo1 {
    public static void main(String[] args) {
        Student student=new Student();
        student.setAge(15);
        student.setName("张三");
        student.setScore(90);
        student.tell();
        System.out.println("..............................");
        System.out.println("name:"+student.getName()+";age:"+student.getAge()+";score:"+student.getScore());
    }
}
 
class Person{
    private int age;
    private String name;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
 
class Student extends Person{
    //private int age;
    //private String name;
        private int score;
      //public int getAge() {
    //return age;
    //}
    //public void setAge(int age) {
    //this.age = age;
    //}
    //public String getName() {
    //return name;
    //}
    //public void setName(String name) {
    //this.name = name;
        //}
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
    public void tell(){
        System.out.println("name:"+getName()+";age:"+getAge()+";score:"+getScore());
    }
}

输出结果:
name:张三;age:15;score:90
..............................
name:张三;age:15;score:90


2.1 在Java中只允许单继承(一个子类只允许有一个父类),子类不能直接访问父类的私有成员
示例2:

public class ExtendsDemo2 {
 public static void main(String[] args){
 PetWorker petWorker=new PetWorker();
 petWorker.setAge(20);
 petWorker.setWork("teacher");
 petWorker.tell();
 }
}
/**
 * 创建类People
 * @author Admin
 *
 */
class People{
    private int age;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
/**
 * 创建Worker类,单继承People类
 * @author Admin
 *
 */
class Worker extends People{
    private String work;
    public String getWork() {
        return work;
    }
    public void setWork(String work) {
        this.work = work;
    }
}
/**
 * 创建PetWorker类,单继承Worker类
 * @author Admin
 *
 */
class PetWorker extends Worker{
    public void tell() {
        System.out.println("age:"+getAge()+";work:"+getWork());
    }
}

输出结果:
age:20;work:teacher


2.2 Java方法重写
  定义:方法名称相同,返回值类型相同,参数也相同,其实质就是子类定义了和父类同名的方法。
  重写限制:被子类重写的方法不能拥有比父类方法更严格的访问权限。private<default<public
  子类调用父类中的方法:super.方法名(参数)
public class ExtendsDemo1 {
    public static void main(String[] args) {   
    B b=new B();
    b.tell();
    }
}
 
class A{
    public void tell(){
      System.out.println("父类中的tell方法");
    }
}
 
class B extends A{
    public void tell() {
    super.tell();
    System.out.println("我重写了tell方法");
    }
    void say(){
    super.tell();
    }
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/a88d744f8421d9fcdc5ed7eaf7b9abb4.html