java开发实战学习笔记3
1.final修饰符
final修饰符修饰的类称为最终类---不能被继承;final修饰的成员变量为常量,不能修改;final修饰的方法不能被覆盖。
2.抽象类
抽象类的作用是:作为类的“模板”,专门作为被继承的类。
抽象类的规则:
(1)包含一个抽象方法的类,必须是抽象类
(2)抽象类和抽象方法需要使用abstract修饰。
(3)抽象方法只需要声明,而不用实现。
(4)不能直接定义抽象类,抽象类只能被继承。
(5)抽象类有构造方法。
abstract class Person { private String name; private int age; public void setName(String name) { this.name=name; } public String getName() { return this.name; } public void setAge(int age) { this.age=age; } public int getAge() { return this.age; } public Person(int age,String name) { this.setAge(age); this.setName(name); } public Person() { this(12,"张三"); } public abstract void sayInfo(); } class Student extends Person{ private String scholl; public void setScholl(String scholl) { this.scholl=scholl; } public String getScholl() { return this.scholl; } public void sayInfo() { System.out.println("name:"+super.getName()+"age:"+getAge()+"scholl:"+this.getScholl()); } public Student() { } } public class Test { public static void main(String[] args) { // TODO, add your application code System.out.println("Hello World!"); Student student=new Student(); student.setScholl("重庆大学"); student.sayInfo(); } } 结果: Hello World! name:张三age:12scholl:重庆大学
3.接口:可以看做一种特殊的抽象类,有全部变量和公共方法组成。
在接口中的成员如果不写public则也是public的。成员变量不写public static ,成员变量也是public static 的。
4.多态:
class A{ public void fun1() { System.out.println("A->fun1"); } } class B extends A{ public void fun1() { System.out.println("B->fun1"); } } class C extends B{ public void fun1() { System.out.println("C->fun1"); } } public class Test { public static void fun(A a) { a.fun1(); } public static void main(String[] args) { // TODO, add your application code System.out.println("Hello World!"); fun(new A()); fun(new B()); fun(new C()); } } 结果: A->fun1 B->fun1 C->fun1
抽象类用来制定模板,接口用来制定标准。