csc 143 introduction
play

CSC 143 Introduction Classes have proven very useful They help us - PDF document

CSC 143 Introduction Classes have proven very useful They help us write programs the way we Inheritance view the world: interface vs implementation There is more to come! Java supports object oriented programming, i.e.,


  1. CSC 143 Introduction  Classes have proven very useful  They help us write programs the way we Inheritance view the world: interface vs implementation  There is more to come! Java supports object oriented programming, i.e.,  Inheritance (sub classing)  Dynamic dispatch (polymorphism)  Two very powerful programming tools!  They help us write less code 1 2 Composition: has-a relationship Organization hierarchy  We have used many times several classes  Often, we classify things according to a together, e.g., hierarchy (from general to specific), e.g.  Use an instance of a class as an instance part of the organization of a university field of another class UniversityMember public class Landscape { private Mountain m = new Mountain(); Staff Faculty Student }  This a "has-a" relationship Freshman Sophomore  A Landscape "has-a" Mountain Lecturer Professor  Also called aggregation 3 4

  2. Inheritance: is-a relationship Inheritance in Java  Inheritance is a way to encode the "is-a" relation  Objects have also an "is-a" relationship in OO languages  Freshman declares that it "is-a" Student by  A Freshman "is-a" Student , a Lecturer inheriting from it "is-a" UniversityMember  A derived class inherits from a base class by  Java gives us the tools to implement an "is- writing " extends BaseClassName " in the derived class declaration base class a" relation. We can map our view of the derived class (or superclass) world on the computer (or subclass) public class Freshman extends Student { /* Freshman-specific stuff here */} 5 6 What is inherited? (1) What is inherited? (2)  The subclass inherits all of the public or  private members of the superclass are unavailable outside the superclass scope. protected or private members(data+methods)  package level members of the superclass are of its superclass (= everything but constructors)  Members declared public or protected within unavailable outside the package scope. If the superclass and subclass are in the same the superclass can be used by the subclass as package, the subclass can access any if they were declared within the subclass itself. package level members of the superclass  protected member of a class: visible within the  A subclass instance is also a superclass class itself, the package of the class, and the instance (is-a relation). subclasses (even if they are in a different  All methods of the superclass can be used on package). More on protected later. a subclass instance. 7 8

  3. Scope example Example: Person, Student  Base.java  A person has a name, an age and can speak package org.seattlecentral;  A student is a person with a gpa public class Base { public int i; //visible everywhere int j;//visible within the package protected int k; //visible within Person // the package and any derived class name: String private int l;// visible within Base only derived from }  Derived.java age: int import edu.seattlecentral.Base; speak: void public class Derived extends Base{ Student public void update(){ i=4; // OK gpa: double j=5; //Error, not in the same package k=6; // OK 9 10 l=7; /*Error (not in Base)*/}} Person class Student class public class Person{ public class Student extends Person{ private double gpa; public String name; // any name is OK public Student(){ private int age; // 0<=age<=130 // Person() called automatically public Person(){ gpa = 3.5;} //Call the other constructor public Student(String s,int a,double g) this("someone",20);} { public Person(String s, int a){ //Call the constructor Person (s,a) name = s; setAge(a); } super(s,a); //Don't write Person(s,a) public void setAge(int a){ setGPA(g); if (a>=0 && a<=130) age=a;} } public void setGPA(double g){ public int getAge(){return age;} if (g>=0 && g<=4.0) gpa=g;} public void speak(){ public double getGPA(){return gpa;} System.out.println("Hi, I am "+name);} } } 11 12

  4. Using Person and Student Static and dynamic types // Can also write Person r = new Student("Sandra",28,3.9); Person p = new Person("Jane",25);  The type used to declared r is Person = static type of Student s = new Student("Robert",28,3.8); r p.speak(); // a person can speak s.speak(); // a student can speak, since  r points to a Student object. Student is the dynamic // a student is a person type of r.  The static type of a variable never changes.  The dynamic type may change r = new Person(“Sandra, 28); // Dynamic type = Person  Or may not be defined r = null; 13 14 Method overriding this keyword revisited  this: two uses  How can we specialize speak for the Student  a reference to the current object when within class? one of the object instance methods  Redefine speak within the Student class  Use this( argument list ) when calling another public void speak(){ constructor from a constructor (within the same super.speak();//let the Person speak class). The call must be the first executed // Add what the student say statement in the constructor. System.out.println("My gpa is "+gpa); public Person(){ } System.out.println  For any Student instance s, s.speak() ("Default constructor"); invokes the speak method of the Student this(name,20); /*Error*/} class. This is called method overriding. 15 16

  5. super keyword Constructor calls  super: two uses  When calling a constructor, Java  invokes the base class constructor (if  a reference to the base object part of the necessary via an implicit call to super()). current derived object within one of the derived  initializes the instance variables of the current object instance method. class super.speak();//In Student.speak()  executes the statements in the constructor of  Use super( argument list ) when calling a base the current class. constructor from a derived constructor. The call public class Derived extends Base{ must be the first executed statement in the private int i=3; constructor. public Derived(){i++;}} super(s,a);//In Student constructor Derived d = new Derived(); // call Base(), set i to 3, increment i  Can't chain the super calls // What happens if Base is derived from super.super.method();//Error // some other class? 17 18 Overloading and Overriding Polymorphism example  Method overloading: same name but a different  Consider number or type of arguments. Person[] group=new Person[2];  A subclass can define some overloaded group[0]=new Person("Jane",25); methods that augment the inherited group[1]=new Student("Bob",26,3.9); overloaded methods provided by a superclass. //OK, a Student is a Person  Method overriding: define a method in the for(int i=0; i<2; i++) subclass with the same signature (return type group[i].speak(); and arguments) as the inherited method. // What is printed?  The method in the subclass shadows the method of the superclass.  Powerful when dealing with a hierarchy of objects (polymorphism: next slide) 19 20

  6. Polymorphism Dynamic binding and Polymorphism  Polymorphism uses dynamic binding  If there are several implementations of a  The selection of the method is done at run method in the inheritance hierarchy of time. The JVM starts looking in the dynamic an object, the one in the most derived type of the variable  In Java, instance methods are by default class always overrides the others.  This is the case even if we refer to the dynamic (not the case in C++). To prevent overriding, declare the method final. object by way of a less derived type. public final void speak() group[1].speak(); { /* speak code in Person */} //invokes speak of Student = dynamic  Can’t write in Student class // type of group[1] public void speak(){/* code */} // Compilation error 21 22 Static binding and Overloading Static methods (1)  Reminder: static methods are not attached to  Overloading uses static binding any instance of a class. They belong to the  The selection of the method is done at compile class. time.  A static method is invoked by using the class  If in the Student class, we write instead name. They are bound at compile time public void speak(String s){ (That's why they are called static) //overload speak of Person Math.sqrt(2); //takes a String as a formal parameter  A static method can't be overridden. super.speak(); System.out.println(s);}  You can't declare in a subclass as a non  Then static method a superclass static method. Person p = new Student();  However, you can shadow a superclass p.speak(); //invokes Person.speak() static method in the subclass (unless the superclass method was declared final). 23 24

  7. Static methods (2) final keyword  final public class Base{  When applied to a method, the method can't be public static void foo(){ System.out.println("foo of Base");} overidden (or shadowed for a static method) }  When applied to a class, the class can't be inherited. public class Derived extends Base{ public void foo(){/*Code*/} // Error public final class ThisIsIt{ public static void foo(){ // OK // class code } System.out.println("foo of Derived");} public class MoreOfIt extends ThisIsIt {} } // Error  None of the methods in a final class are overridden. The compiler can optimize the use of the class methods (inlining). 25 26

Recommend


More recommend