详述继承

详述继承

1、继承的目的
根据访问权限修饰符的不同,子类可以继承父类中某些成员变量和方法,提高了代码的重用性,子类也可以添加新的成员变量和方法

public class Father {
	String name;
	String id;
	String address;
	String mobile;
	public Object eat() {
		System.out.println("正在吃饭.......");
	}
}
public class Student extends Father {
	int mobile;	
	public static void main(String[] args) {
		Student student = new Student();
		student.eat();
	}
}

在这里插入图片描述
2、什么是继承?
继承是面向对象编程的三大特征之一,是一种基于已有类来创建新类的机制。由继承而得到的类称为子类(或派生类),被继承的类称为父类(或超类)。
Java中每个类只允许有一个父类。语法如下:class <子类> extends <父类>
如果一个类没有显式继承某个类则该类默认继承Object,子类可以继承父类的某些属性或方法(但一定不能被private修饰)

public class Father {
	String name;
	String id;
	String address;
	String mobile;
	public Object eat() {
		System.out.println("正在吃饭.......");
	}
}
public class Student extends Father {
		public static void main(String[] args) {
		Student student = new Student();
		student.name = "李雷"
		System.out.println(student.name);
		student.eat();
	}
}

在这里插入图片描述
3、怎么继承?
①如果子类中的属性与父类中属性重复,则子类中调用该属性使用的是子类的属性
②如果想要调用父类的属性
<1>子类非静态代码块或非静态方法调用父类中重复的属性使用关键字super。
<2>子类静态代码块或静态方法调用父类中重复的属性需要创建父类对象。

public class Father {
	String name;
	String id;
	String address;
	String mobile = "110";
	public Object eat() {
		System.out.println("正在吃饭.......");
		return "rice";
	}
}
public class Student extends Father {
	long mobile = 120;
	public void test() {
		System.err.println(mobile);
		System.err.println(super.mobile);
	}
	static {
		System.out.println(new Student().mobile);
		System.out.println(new Father().mobile);
	}
	public static void main(String[] args) {
		Student student = new Student();
		student.eat();
		student.test();
		System.out.println(student.mobile);
	}

在这里插入图片描述
4、如果类被final修饰,则该类不能被继承,Java中已有的类(诸如Void、String、Class、Scanner、System、8种基本数据类型对应包装类等类)已经被final修饰,所以这些类不能被继承。

public final class Father {
	String name;
	String id;
	String address;
	String mobile;
	public Object eat() {
		System.out.println("正在吃饭.......");
	}
}
public class Student extends Father {
	int mobile;	
	public static void main(String[] args) {
		Student student = new Student();
		student.eat();
	}
}

程序将会报错:The type Student cannot subclass the final class Father

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值