Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Welcome back CS02 students
- Please log in to https://vm.ktbyte.com
- username: "16fa" + <ktbyte_username>
- password: ktbyte
- inheritance
- */
- public class Lesson2 {
- public static void main(String[] args) {
- System.out.println("Hello");
- Animal fisso = new Dog();
- // ok to have Animal variable set to Dog
- fisso.name = "fisso";
- fisso.age = 7;
- fisso.eat();
- // ok as long as fisso has a Dog object
- Dog d = (Dog)fisso;
- System.out.println(d.toy); // error!
- Animal bob = new Cat();
- bob.eat(); // meow
- bob.name = "bob";
- bob.age = 5;
- System.out.println(bob); //
- }
- }
- class Cat extends Animal { // Animal is the super class
- // Overriding the Animal class's eat function!
- void eat() {
- System.out.println(super.name + " meow");
- }
- }
- // class Dog inherits all fields and methods of Animal
- class Dog extends Animal {
- String toy;
- Dog() {
- toy = "dogbone";
- }
- }
- class Animal { // extends Object
- String name;
- int age;
- void eat() {
- System.out.println("om nom nom");
- }
- // overrides the default toString() from Object class
- public String toString() {
- return name + ": " + age;
- }
- }
- // can different classes share fields?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement