Java的封装、继承与多态

封装、继承与多态

  • 封装

封装(Encapsulation)是面向对象方法的重要原则,就是把对象的属性和操作(或服务)结合为一个独立的整体,并尽可能隐藏对象的内部实现细节。

public class Student {
    //封装
    //属性私有
    private String name;
    private String id;
    private String sex;

    //通过get、set方法操作数据

    //get 获取数据
    public String getName() {
        return name;
    }

    public String getId() {
        return id;
    }

    public String getSex() {
        return sex;
    }

    //给数据赋值
    public void setName(String name) {
        this.name = name;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}
  • 继承

继承是从已有的类中派生出新的类,新的类能吸收已有类的数据属性和行为,并能扩展新的能力。

Person父类

public class Person {
    public int a=1;

    public void talk(){
        System.out.println("Person");
    }
}

Student子类

public class Student extends Person{
    public void say(){
        System.out.println("Student");
    }
}

测试用例

public class Application {
    public static void main(String[] args) {
        Student student=new Student();

        System.out.println(student.a);//继承父类的成员变量
        student.say();//子类拓展的方法
        student.talk();//子类继承的方法
    }
}

输出:
1
Student
Person
  • 多态

多态存在的三个必要条件:

  1. 继承
  2. 重写
  3. 父类引用子类对象

Person父类

public class Person {
    public void say(){
        System.out.println("Person");
    }
    public void run(){
        System.out.println("run");
    }
}

Student子类

public class Student extends Person{
    //重写say()方法
    @Override
    public void say() {
        System.out.println("Student");
    }
	
    public void talk(){
        System.out.println("myStudent");
    }
}

测试用例

public class Application {
    public static void main(String[] args) {
        //方法的多态
        Student student=new Student();
        Person person=new Student();
        Person person1=new Person();

        student.say();//调用Student的say()
        person.say();//调用Student的say()
        person1.say();//调用Person的say()
    }
}

输出:
Student
Student
Person
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值