10-23-2013

posted Oct 24, 2013, 5:35 AM by Samuel Konstantinovich   [ updated Oct 24, 2013, 5:35 AM ]
Goal: Inheritance

A class that is derived from another class is called a subclass.
We use the keyword extends (see example of princess below).

All classes are derived from another class, except Object which is the parent of all other classes.

A class can be derived from a class,which is derived from another class and so on. Each class has exactly one direct superclass, if there is no explicit superclass, Object is the default superclass.

A subclass inherits all the non private members of the superclass. (Methods, Instance variables)

Example of a Princess subclass:

public class Character{
    
    protected String name;
    
    public Character(){
        setName("Bob");
    }

    public String toString(){
return name;
    }

    public void setName(String name){
this.name=name;
    }

    public String attackString(String targetName){
return name + " attacks " + targetName;
    }
}



public class Princess extends Character{

    //replace the attack string method with this one
    public String attackString(String targetName){
if(Math.random()<0.5){
   return name + " attacks " + targetName + 
                   " with style.";
}else{
   return name + " performs a duet with her bff" +
                   " and paralyzes " + targetName;
}
    }
}

public class demo{

    public static void main(String[]arrrrrrrrgs){

Character x = new Character();

x.setName("Beowulf");
       

Princess a = new Princess();
a.setName("Zelda");

System.out.println(a.attackString(x.toString()));
System.out.println(x.attackString(a.toString()));
    }
}

Comments