JAVA inheritance, interfaces
Interface 1
public interface IAction1 {
void run();
}
Interface 2
public interface IAction2 {
void run();
}
Animal
class Animal {public
String name; // attribute
int age; // Properties // Default constructor public Animal () {} // parameterized constructors public Animal (String name, int Age) { this.name = name; Age = this.age;} // override the parent class toString @Override public String toString () { return "Animal (" + "name =" + name + '\' '+ ", Age =" + Age +') '; } // override the parent class equls @Override public Boolean the equals (Object obj) { return super.equals (obj);} // interface quickly generate public String getName () { return name;} public void the setName (String name) {
this.name = name; }
public int getAge() {
return age;}
public void setAge(int age) {
this.age = age; }
}
Dog
// inherited Animal (the extends keyword)
// Interface IAction1 (keyword the implements)
public class Animal Dog the extends the implements IAction1 {
// parameterized constructor, call the parent class is configured with parameters (call the parent class keyword Super)
public Dog ( name String, int Age) {
Super (name, Age);}
@Override
public String getName () {
return "Dog";} @Override public void RUN () { System.out.println ( "IAction1.run") ;} // increase the interface 2 public void the addAction (iAction2 iAction2) {iAction2.run ();}}
MAIN
{the Main class public
public static void main (String [] args) {
// Example
Dog dog = new Dog ( "Akita", 1);
// Use internal class object
//dog.addAction(new MyClass ());
// this syntax to do three things: new new IAction2 () {....}
// 1. create an anonymous class
// implements IAction2 2. Interface
// 3. return an anonymous class object
dog.addAction ( IAction2 new new () {
@Override
public void RUN () {
System.out.println ( "IAction2 RUN");}
});
dog.run ();
}
}