Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. /*
  2.  
  3. Welcome back CS02 students
  4.  
  5. Please log in to https://vm.ktbyte.com
  6. username: "16fa" + <ktbyte_username>
  7. password: ktbyte
  8.  
  9.  
  10. inheritance
  11.  
  12. */
  13.  
  14. public class Lesson2 {
  15. public static void main(String[] args) {
  16. System.out.println("Hello");
  17. Animal fisso = new Dog();
  18. // ok to have Animal variable set to Dog
  19. fisso.name = "fisso";
  20. fisso.age = 7;
  21. fisso.eat();
  22.  
  23. // ok as long as fisso has a Dog object
  24. Dog d = (Dog)fisso;
  25. System.out.println(d.toy); // error!
  26.  
  27. Animal bob = new Cat();
  28. bob.eat(); // meow
  29.  
  30. bob.name = "bob";
  31. bob.age = 5;
  32. System.out.println(bob); //
  33. }
  34. }
  35.  
  36. class Cat extends Animal { // Animal is the super class
  37. // Overriding the Animal class's eat function!
  38. void eat() {
  39. System.out.println(super.name + " meow");
  40. }
  41. }
  42.  
  43. // class Dog inherits all fields and methods of Animal
  44. class Dog extends Animal {
  45. String toy;
  46.  
  47. Dog() {
  48. toy = "dogbone";
  49. }
  50. }
  51.  
  52. class Animal { // extends Object
  53. String name;
  54. int age;
  55.  
  56. void eat() {
  57. System.out.println("om nom nom");
  58. }
  59.  
  60. // overrides the default toString() from Object class
  61. public String toString() {
  62. return name + ": " + age;
  63. }
  64. }
  65.  
  66. // can different classes share fields?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement