Java面向对象之类、接口、多态

Java面向对象之类、接口、多态

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,类似于swiftprotocal

interface中的变量都是默认public static final修饰的

interface中的方法都是默认public abstract修饰的

注意点:

  这些修饰词可以省略一个,也可以省略多个(甚至都省略),但是不能用其他修饰词修饰.

  不写public 不是默认的 default;写default会报错

变量:

   public static final int MAX_LENGTH = 1000;

   final int MAX_LENGTH = 1000;

   static int MAX_LENGTH = 1000;

   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();
    }
}

多态使程序更加具有扩展性:向上类型转化、方法的动态绑定

原文地址:https://www.cnblogs.com/jeffersonqin/p/12250308.html