JAVA继承

来源:互联网 发布:兼职网络编辑招聘 编辑:程序博客网 时间:2024/06/02 05:58

一。方法的覆写

需要注意访问权限的使用,子类要用大的访问权限

private:最小的权限

default:什么都不声明,String name;

public:最大的访问权限


如果非要调用被覆写过的方法,可以通过super关键字实现,super关键字从子类访问父类的内容

class Person{void print(){System.out.println("Person__void.print()");}};class Student extends Person{public void print(){super.print();//访问父类方法System.out.println("Student__void.print()");}};public class csdnTest{public static void main(String args[]{Student s =new Student();s.print();}};

二。方法的覆盖与重载


三。super关键字

class Person{// 定义Person类private String name ;// 定义name属性private int age ;// 定义age属性public Person(String name,int age){this.setName(name) ;this.setAge(age) ;}public void setName(String name){this.name = name;}public void setAge(int age){this.age = age ;}public String getName(){return this.name ;}public int getAge(){return this.age ;}public String getInfo(){return "姓名:" + this.getName() + ";年龄:" + this.getAge() ;}};class Student extends Person{// 定义Student类private String school ;// 定义school属性public Student(String name,int age,String school){super(name,age) ;// 明确调用父类中有两个参数的构造this.school = school ;}public void setSchool(String school){this.school = school ;}public String getSchool(){return this.school ;}public String getInfo(){return super.getInfo() + ";学校:" + this.getSchool() ;} };public class SuperDemo01{public static void main(String arsg[]){Student stu = new Student("张三",30,"清华大学");// 实例化子类对象System.out.println(stu.getInfo()) ;}};

四。this和super的区别


五。继承实例

要求:定义一个整型数组类,要求包含构造方法,增加数据及输出数据成员方法,并利用数组实现动态内存分配,并添加以下子类

1.排序类

2.反转类

class Array{// 表示数组private int temp[] ;// 整型数组private int foot ;// 定义添加位置public Array(int len){if(len>0){this.temp = new int[len] ;}else{this.temp = new int[1] ;// 最少维持空间是1个}}public boolean add(int i){// 增加元素if(this.foot<this.temp.length){// 还有空间this.temp[foot] = i ;// 增加元素this.foot ++ ;// 修改脚标return true ;}else{return false ;}}public int[] getArray(){return this.temp ;}};class SortArray extends Array{// 排序类public SortArray(int len){super(len) ;}public int[] getArray(){// 覆写方法java.util.Arrays.sort(super.getArray()) ;// 排序操作return super.getArray() ;}};class ReverseArray extends Array{// 反转操作类public ReverseArray(int len){super(len) ;}public int[] getArray() {int t[] = new int[super.getArray().length] ;// 开辟一个新的数组int count = t.length - 1 ;for(int x=0 ;x<t.length;x++){t[count] = super.getArray()[x] ;// 数组反转count-- ;}return t ;}};public class ArrayDemo{public static void main(String args[]){// ReverseArray a = null ;// 声明反转类对象// a = new ReverseArray(5) ;// 开辟5个空间大小SortArray a = null ;a = new SortArray(5) ;System.out.print(a.add(23) + "\t") ;System.out.print(a.add(21) + "\t") ;System.out.print(a.add(2) + "\t") ;System.out.print(a.add(42) + "\t") ;System.out.print(a.add(5) + "\t") ;System.out.print(a.add(6) + "\t") ;print(a.getArray()) ;}public static void print(int i[]){// 输出数组内容for(int x=0;x<i.length;x++){System.out.print(i[x] + "、") ;}}};



0 0
原创粉丝点击