class Person { // 实例属性 int age; String name; // 类属性 static int v = 1; // 构造器 public Person() {} // 构造器重载 public Person(int age, String name) { this.age = age; this.name = name; } // 实例方法 public void tell_age() { System.out.println(this.age); } // 方法重载 public void tell_age(String s) { System.out.println(this.age + " " + s); } // 类方法 public static void print_v() { System.out.println(v); } } // 类的继承 // 继承能够继承除了private的一切方法和属性 // Object是Java的顶级父类 class Man extends Person { // 方法覆盖 @Override public void tell_age() { super.tell_age(); // 执行父类的此方法 System.out.print("Man eat..."); } }
指interface
,相似于swift
的protocal
java
interface中的变量都是默认public static final修饰的swift
interface中的方法都是默认public abstract修饰的ide
注意点:this
这些修饰词能够省略一个,也能够省略多个(甚至都省略),可是不能用其余修饰词修饰.code
不写public 不是默认的 default;写default会报错对象
变量:blog
public static final int MAX_LENGTH = 1000;继承
final int MAX_LENGTH = 1000;接口
static int MAX_LENGTH = 1000;class
public int MAX_LENGTH = 1000;
int MAX_LENGTH = 1000;
方法:
public abstract void method();
public void method();
abstract void method();
void method();
interface Animal { public void eat(); public void sleep(); public void play(); } interface Fish extends Animal { public void swim(); } class AFish implements Fish { @Override public void swim() { } @Override public void sleep() { } @Override public void play() { } @Override public void eat() { } } // 固然,一个类也能够实现多个interface 彼此之间用逗号隔开: // class ClassA implements interfaceA, interfaceB, interfaceC { // // }
public class Demo { public static void main(String[] args) { Cat c = new Cat(); // Java 多态 一个方法有多种状态 Animal cat = new Cat(); Animal dog = new Dog(); cat.eat(); // cat eat ... cat.sleep(); // cat sleep... dog.eat(); // dog eat ... dog.sleep(); // dog sleep... Person p = new Person(); p.care(cat); p.care(dog); } } interface Animal { public void eat(); public void sleep(); } class Cat implements Animal { @Override public void eat() { System.out.println("cat eat..."); } @Override public void sleep() { System.out.println("cat sleep..."); } } class Dog implements Animal { @Override public void eat() { System.out.println("dog eat..."); } @Override public void sleep() { System.out.println("dog sleep..."); } } class Person { public void care(Animal a) { a.sleep(); a.eat(); } }
多态使程序更加具备扩展性:向上类型转化、方法的动态绑定