I read through all "the book" and it writes that no inheritance in Rust.
However, can we implement a feature similar to inheritance for Rust?
And why wouldn't Rust allow inheritance even just single inheritance like that in Java?
The reason I ask these two question is that I feel traits seems as powerful as inheritance because public attributes and methods can be inherited in Java by child classes and therefore inherited methods can use inherited attributes with no doubt, but traits only can ensure that methods of it and its super traits are implemented while attributes are not guaranteed, so the default method implementations of a trait seem to be weak.
Like we can do this without extra implementation in Java
public class People
{ int eatenApple =0;
public void eatApple(){ eatenApple++; System.out.printf("%d apple eaten",eatenApple); }
}
public class Student extends People
{ //other attributes and methods specificly related to Student
}
// in main
Student s = new Student();
s.eatApple();
However we seem not to be able to do this without extra implementation for type Student
in Rust.
Say we define a trait EatApple
like below, we still need to set an attribute for type Student
and implement the trait with exactly the same code.
pub trait EatApple{
fn eat_apple(){ println!("by default I don't know how many apples were eaten"); }
}
If we can define attributes(not only const and static like in Java) in traits, than we can do the similar thing as the inheritance dose in this example in Java. Like
pub trait EatApplePlus{
eaten_apple : i32;
fn eat_apple(){ println!("{} apple eaten", eaten_apple); }
}