Week 1 - Inheritance-PART A (4).pptx

Full Transcript

Chapter 7: Inheritance CS 231: PROGRAMMING II 7.1: Inheritance Basic Review: Class User-defined data types Defined using the “class” keyword Each class has associated Data members (any object type) Methods that operate on the data New instances of the class are declared using...

Chapter 7: Inheritance CS 231: PROGRAMMING II 7.1: Inheritance Basic Review: Class User-defined data types Defined using the “class” keyword Each class has associated Data members (any object type) Methods that operate on the data New instances of the class are declared using the “new” keyword “Static” members/methods have only one copy, regardless of how many instances are created Derived Class Inheritance : Defined Derived Class (subclass- child class) vs Base Class (superclass – parent class) Inherited member ( all instances variable, all the static variable and all the public methods of base class) overriding a method definition final modifier Changing access permission of an overridden method (in derived class)  Allowed - : private to public  Not allowed : public to private Overriding vs overloading super vs this constructor Terminology Inheritance is a fundamental Object Oriented concept A class can be defined as a "subclass" of another class. superclass: Person The subclass inherits all data attributes of its superclass - name: String The subclass inherits all methods of its superclass - dob: Date The subclass inherits all associations of its superclass The subclass can: Add new functionality subclass: Employee Use inherited functionality - employeeID: int Override inherited functionality - salary: int - startDate: Date Introduction - inheritance Usage: For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability. Terms used: Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. Inheritance (Syntax) a subclass inherits all of the superclass's behavior and can override methods. To call an overridden method from the superclass, use the super keyword: Inheritance Hierarchy: Inheritance creates a class hierarchy  Classes higher in the hierarchy are more general and more abstract  Classes lower in the hierarchy are more specific and concrete Class There is no limit to the number of subclasses a class can have Class Class Class There is no limit to the depth of the class tree Class Class Class Class Example 1:  Inheritance is declared using the "extends" keyword Syntax: modifier(s) class ClassName extends ExistingClassName { memberList } public class Circle extends Shape {... Why is this useful in programming? } Allows for code reuse More intuitive/expressive code Example 2: public class Person Person is said to be {  the parent class of Person Employee - name: String private String name; - dob: Date private Date dob;  the super class of [...] Employee  the base class of Employee public class Employee extends Person  an ancestor of Employee { private int employeID; Employee is said to be Employee private int salary;  a child class of Person - employeeID: int private Date startDate; - salary: int  a sub class of Person - startDate: Date [...]  a derived class of Person  a descendant of Person Employee anEmployee = new Employee(); Brainstorming: Inheritance What are some other examples of possible inheritance hierarchies? Person -> student, faculty… Shape -> circle, triangle, rectangle… Other examples??? Types of inheritance: not supported in Java through class Multiple inheritance - When one class inherits multiple classes multiple inheritance is not supported in java: a class cannot extend more than one class Why ? - reduce the complexity and simplify the language a class can implement one or more interfaces, which has helped Java get rid of the impossibility of multiple inheritance Overriding Methods Subclasses inherit all methods from their superclass any method that is not final may be overridden by a descendant class same signature as method in ancestor A subclass can override (redefine) the methods of the superclass  Objects of the subclass type will use the new method  Objects of the superclass type will use the original  Advantage : class can give its own specific implementation to a inherited method without even modifying the parent class code. class Box class Rectangle public double area() { public double area() return 2 * (getLength() * getWidth() { + getLength() * height return getLength() * getWidth(); + getWidth() * height); } } Example: Overriding Methods Super keyword in Method Overriding The super keyword is used for calling the parent class method/constructor. super.myMethod() calls the myMethod() method of base class super() calls the constructor of base class class Demo extends ABC { class ABC public void myMethod() { { public void myMethod() //This will call the myMethod() of parent class { super.myMethod(); System.out.println("Overridden System.out.println("Overriding method"); method"); } } } public static void main( String args[]) { Demo obj = new Demo(); Output: obj.myMethod(); Class ABC: mymethod() } Class Test: mymethod() } final Methods Methods can be qualified with the final modifier Final methods cannot be overridden. This can be useful for security purposes. public final boolean validatePassword(String username, String Password) { [...] Classes can be qualified with the final modifier The class cannot be extended This can be used to improve performance. Because there can be no subclasses, there will be no polymorphic overhead at runtime. public final class Color { [...] Defining Constructors of the Subclass Call to constructor of superclass: Must be first statement Specified by super parameter list public Box() { Example 1: super(); height = 0; } public Box(double l, double w, double h) { super(l, w); Example 2: height = h; } this vs super keyword THIS KEYWORD SUPER KEYWORD Usage : Usage : 1. this can be used to refer current class 1. super() invokes the constructor of the instance variable. parent class. 2. this can be used to invoke current class method (implicitly) 2. super.variable_name refers to the variable in the parent class. 3. this() can be used to invoke current class constructor. 3. super.method_name refers to the method 4. this can be passed as an argument in the of the parent class. method call. 5. this can be passed as argument in the constructor call. 6. this can be used to return the current class instance from the method. this keyword Usage : this can be used to refer current class instance variable. this can be used to invoke current class method (implicitly) this() can be used to invoke current class constructor. this can be passed as an argument in the method call. this can be passed as argument in the constructor call. this can be used to return the current class instance from the method. problem if we don't use this keyword class Student { int rollno; class TestThis1{ String name; public static void main(String args[]){ float fee; Student s1=new Student(111,"asma",5000f); Student s2=new Student(112,"samar",6000f); Student(int rollno,String name,float fee) s1.display(); { s2.display(); rollno=rollno; }} name=name; fee=fee; } void display() { System.out.println(rollno+" "+name+" Output : "+fee); } 0 null 0.0 } 0 null 0.0 Solution of the previous problem by this keyword class Student { class TestThis1 int rollno; { String name; public static void main(String args[]) float fee; { Student s1=new Student(111,“fahad",5000f); Student(int rollno,String name,float fee) Student s2=new Student(112,“ali",6000f); { this.rollno=rollno; s1.display(); this.name=name; s2.display(); this.fee=fee; } } } void display() { System.out.println(rollno+" "+name+" Output : "+fee); } 111 fahad 5000 } 112 ali 6000 …when this keyword is not required class Student { class TestThis1 int rollno; { String name; public static void main(String args[]) float fee; { Student s1=new Student(111,“asma",5000f); Student(int r,String n,float f) { Student s2=new rollno=r; Student(112,"samar",6000f); name=n; fee=f; s1.display(); } s2.display(); } void display() } { System.out.println(rollno+" "+name+" Output : "+fee); } 111 asma 5000 } 112 samar 6000 this: to invoke current class method class A { void m() class Test { System.out.println("hello m"); } { public static void main(String args[]) void n() { { A a=new A(); System.out.println("hello n"); a.n(); //m(); //same as this.m() } this.m(); } } } Output : hello n hello m this() : to invoke current class constructor Calling default constructor from parameterized constructor: class A { class Test A() { { System.out.println("hello a"); } public static void main(String args[]) { A(int x) A a=new A(10); { } this(); } System.out.println(x); } } Output : hello a 10 this() : to invoke current class constructor Calling parameterized constructor from default constructor: class A { class Test A() { { public static void main(String args[]) this(5); { System.out.println("hello a"); A a=new A(); } } } A(int x) { System.out.println(x); } Output : } 5 hello a Real usage of this() constructor call class Student { class Test int rollno; String name,course; float fee; { public static void main(String args[]) Student( int rollno,String name,String course) { { Student s1=newStudent(111,“fahad","java"); this.rollno=rollno; Student s2=newStudent(112,“khalid","java",6000f); this.name=name; this.course=course; } s1.display(); s2.display(); Student(int rollno,String name,String } course,float fee) } { this(rollno,name,course);//reusing constructor Output : this.fee=fee; } 111 fahad java null void display(){System.out.println(rollno+" 112 khalid java 6000 "+name+" "+course+" "+fee);} } Real usage of this() constructor call - error class Student { class Test int rollno; String name,course; float fee; { public static void main(String args[]) Student( int rollno,String name,String course) { { Student s1=newStudent(111,“asma","java"); this.rollno=rollno; Student s2=newStudent(112,"samar","java",6000f); this.name=name; this.course=course; s1.display(); } s2.display(); } Student(int rollno,String name,String } course,float fee) { this.fee=fee; this(rollno,name,course);//error Output : } void display(){System.out.println(rollno+" Compile Time Error: Call to this must be first statement in "+name+" "+course+" "+fee);} constructor } this: to pass as an argument in the method class S2 { void m(S2 obj) { System.out.println("method is invoked"); } void p() { m(this); } public static void main(String args[]) { S2 s1 = new S2(); s1.p(); Output : } } method is invoked this: to pass as argument in the constructor call class B class A4 { { A4 obj; int data=10; B(A4 obj) { A4() this.obj=obj; { } B b=new B(this); b.display(); void display() } { System.out.println(obj.data); public static void main(String args[]) //using data member of A4 class { } A4 a=new A4(); } } } Output : 10 this keyword can be used to return current class instance Exmaple: Syntax: class A return_type method_name() { { A getA() return this; { } return this; } void msg(){System.out.println("Hello java");} Output : } Hello java class Test { public static void main(String args[]) { new A().getA().msg(); } } super keyword  used inside a sub-class method definition to call a method defined in the super class Private methods of the super-class cannot be called. Only public and protected methods can be called by the super keyword Usage : super() invokes the constructor of the parent class. super.variable_name refers to the variable in the parent class. super.method_name refers to the method of the parent class. super() invokes the constructor of the parent class class ParentClass public class SubClass extends ParentClass { { public ParentClass() public SubClass() { { System.out.println("Parent Class default System.out.println("Child Class default Constructor"); Constructor"); } } } public static void main(String args[]) { SubClass s = new SubClass(); Output : } } Parent Class default Constructor Child Class default Constructor super() invokes the constructor of the parent class class ParentClass public class SubClass extends ParentClass { { public ParentClass() public SubClass() { { System.out.println("Parent Class default super(); Constructor"); System.out.println("Child Class default } Constructor"); } } public static void main(String args[]) { Output : SubClass s = new SubClass(); } Parent Class default Constructor } Child Class default Constructor super.variable refers to the variable in the parent class class ParentClass public class SubClass extends ParentClass { { int val=999; int val=123; } public void disp() { System.out.println("Value is : "+val); } public static void main(String args[]) { Output : SubClass s = new SubClass(); s.disp(); Value is : 123 } } super.variable refers to the variable in the parent class class ParentClass public class SubClass extends ParentClass { { int val=999; int val=123; } public void disp() { System.out.println("Value is : "+super.val); } public static void main(String args[]) { Output : SubClass s = new SubClass(); s.disp(); Value is : 999 } } super.method refers to the method of the parent class class ParentClass public class SubClass extends ParentClass { { public void disp() public void disp() { { System.out.println("Parent Class method"); System.out.println("Child Class method"); } } } public void show() { disp(); } public static void main(String args[]) Output : { SubClass s = new SubClass(); Child Class method s.show(); } } super.method refers to the method of the parent class class ParentClass public class SubClass extends ParentClass { { public void disp() public void disp() { { System.out.println("Parent Class method"); System.out.println("Child Class method"); } } } public void show() { //Calling SubClass disp() method disp(); //Calling ParentClass disp() method Output : super.disp(); Child Class method } Parent Class method public static void main(String args[]) { SubClass s = new SubClass(); s.show(); } } super.method refers to the method of the parent class class ParentClass public class SubClass extends ParentClass { { public void disp() public void show() { { System.out.println("Parent Class method"); disp(); } } } public static void main(String args[]) { SubClass s = new SubClass(); s.show(); } Output : } Parent Class method Review What is inheritance? What is a superclass? What is a subclass? Which class is at the top of the class hierarchy in Java? What are the constructor issues surrounding inheritance? What is method overriding? What is a final method? What is a final class?

Use Quizgecko on...
Browser
Browser