更新時(shí)間:2023-10-09 來(lái)源:黑馬程序員 瀏覽量:
Java中的面向?qū)ο筇卣魍ǔV傅氖欠庋b、繼承和多態(tài)。以下是一個(gè)基本的示例,幫助我們了解如何在Java中使用這些特征:
封裝是指將對(duì)象的狀態(tài)和行為打包在一個(gè)單元中。通過(guò)將數(shù)據(jù)字段聲明為私有的,并提供公共的getter和setter方法來(lái)訪問(wèn)和修改它們,可以實(shí)現(xiàn)封裝。例如:
public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
繼承是指一個(gè)對(duì)象獲得另一個(gè)對(duì)象的屬性和方法。在Java中,通過(guò)使用extends關(guān)鍵字來(lái)實(shí)現(xiàn)繼承。例如,我們可以創(chuàng)建一個(gè)Student類,它繼承自Person類:
public class Student extends Person { private String major; public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } }
多態(tài)是指一個(gè)對(duì)象有多種形式。在Java中,多態(tài)可以通過(guò)方法重寫和向上轉(zhuǎn)型來(lái)實(shí)現(xiàn)。例如,我們可以創(chuàng)建一個(gè)Teacher類,它重寫了Person類的getName()方法:
public class Teacher extends Person { @Override public String getName() { return "Teacher: " + super.getName(); } }
現(xiàn)在,我們可以創(chuàng)建一個(gè)Student和Teacher的對(duì)象,并將它們向上轉(zhuǎn)型為Person:
public class Main { public static void main(String[] args) { Student student = new Student(); student.setName("John"); student.setAge(18); student.setMajor("Computer Science"); Teacher teacher = new Teacher(); teacher.setName("Mrs. Smith"); teacher.setAge(35); Person[] people = {student, teacher};