Java Inheritance

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

In Java, a class can only inherit from __________.... However: you can implement from _____....

- In Java, a class can only inherit from ONE superclass. - However: you can implement from MANY interfaces! THINK about the animals example that we used: When we extend from the Animal superclass- whatever methods are in the Animal class must be applicable to ALL subclasses: Not all animals can walk or fly. IF an animal- say a Dog, can walk: it will EXTEND Animal- and it will IMPLEMENT walk (if we create a "walk" interface) A bird can walk AND fly: it will EXTEND Animal, it will IMPLEMENT walk, AND it will IMPLEMENT fly!

Important differences between static and dynamic binding

1. Static binding in Java occurs during compile time while - dynamic binding occurs during runtime. 2. private, final and static methods and variables use static binding and are bonded by compiler while - virtual methods are bonded during runtime based upon runtime object. 3. Static binding uses Type (class in Java) information for binding while - dynamic binding uses object to resolve binding. Overloaded methods are bonded using static binding while - overridden methods are bonded using dynamic binding at runtime.

Which of the following is not valid ? A. Student s = new Student(); B. Student g = new GradStudent(); C. Student u = new UnderGrad(); D. GradStudent g = new Student(); E. UnderGrad u = new Student(); 1. C, D, E are not valid 2. A, B, C are not valid 3. D is not valid 4. E is not valid 5. D & E are not valid

5 is correct. as a Student is not necessarily a GradStudent nor an UnderGrad, D and E are not Valid declarations. A, B and C are valid as GradStudent is-a Student, and an UnderGrad is-a Student.

Which of the following is true about inheritance in Java. 1) In Java all classes inherit from the Object class directly or indirectly. The Object class is root of all classes. 2) Multiple inheritance is not allowed in Java. 3) Unlike C++, there is nothing like type of inheritance in Java where we can specify whether the inheritance is protected, public or private. (A) 1, 2 and 3 (B) 1 and 2 (C) 2 and 3 (D) 1 and 3

Answer: (A)

Polymorphism

Polymorphism in Java has two types: 1. Compile time polymorphism (static binding) - Method overloading is an example of static polymorphism, while 2. Runtime polymorphism (dynamic binding). - Method overriding is an example of dynamic polymorphism.

What are interfaces? What does an interface do/allow us to do?

WHAT IS AN INTERFACE: An interface specifies methods that a particular class (which implements the interface) MUST use. The interface itself is ABSTRACT: this means there is no actual code for any of the methods IN the interface- you just provide the method names/parameters. The actual code still goes in the CLASS that you're creating. WHAT IT ALLOWS US TO DO: The idea is to use an interface to provide a common behavior that can be used by several classes by having them all implement the same interface. This is a way to STANDARDIZE the way a particular SET OF CLASSES is used.

Is Overiding possible with private methods? Predict the output of following program. class Base { private void fun() { System.out.println("Base fun"); } } class Derived extends Base { private void fun() { System.out.println("Derived fun"); } public static void main(String[] args) { Base obj = new Derived(); obj.fun(); } }

We get compiler error "fun() has private access in Base" (See this). So the compiler tries to call base class function, not derived class, means fun() is not overridden.

Top-down development

a development order that implements top-level modules and main classes first and subsidiary classes later. High level classes are broken down into subsidiary classes.

A constructor's name must be identical to it's ______ name

class

Static Binding or Compile time Polymorphism (Overloaded functions)

class DemoOverload{ public int add(int x, int y){ //method 1 return x+y; } public int add(int x, int y, int z){ //method 2 return x+y+z; } public int add(double x, int y){ //method 3 return (int)x+y; } public int add(int x, double y){ //method 4 return x+(int)y; } } class Test{ public static void main(String[] args){ DemoOverload demo=new DemoOverload(); System.out.println(demo.add(2,3)); //method 1 called System.out.println(demo.add(2,3,4)); //method 2 called System.out.println(demo.add(2,3.4)); //method 4 called System.out.println(demo.add(2.5,3)); //method 3 called } } In the above example, there are four versions of add methods. The first method takes two parameters while the second one takes three. For the third and fourth methods there is a change of order of parameters. The compiler looks at the method signature and decides which method to invoke for a particular method call at compile time.

Dynamic Binding or Run-time Polymorphism

class Vehicle{ public void move(){ System.out.println("Vehicles can move!!"); } } class MotorBike extends Vehicle{ public void move(){ System.out.println("MotorBike can move and accelerate too!!"); } } class Test{ public static void main(String[] args){ Vehicle vh=new MotorBike(); vh.move(); // prints MotorBike can move and accelerate too!! vh=new Vehicle(); vh.move(); // prints Vehicles can move!! } } the first call to move(), the reference type is Vehicle and the object being referenced is MotorBike. So, when a call to move() is made, Java waits until runtime to determine which object is actually being pointed to by the reference. In this case, the object is of the class MotorBike. So, the move() method of MotorBike class will be called. In the second call to move(), the object is of the class Vehicle. So, the move() method of Vehicle will be called.

procedural abstraction

is the use of helper methods in a class

Keyword that must be used to 'activate' a constructor

new

How do you implement an interface: i.e. how do you say in Java "this class is going to use XYZ interface"?

1. You use the "implements" keyword: public class DeskPhone implements ITelephone { 2. You actually implement ALL of the interface methods: The declaration line (ABOVE) will remained underlined in red (an error) until ALL the interface's methods are implemented.

What is the output ? class Base { public void show() { System.out.println("Base::show() called"); } } class Derived extends Base { public void show() { System.out.println("Derived::show() called"); } } public class Main { public static void main(String[] args) { Base b = new Derived();; b.show(); } } (A) Derived::show() called (B) Base::show() called

Answer: (A) Explanation: In the above program, b is a reference of Base type and refers to an abject of Derived class. In Java, functions are virtual by default. So the run time polymorphism happens and derived fun() is called.

Output of following Java program? class Base { public void Print() { System.out.println("Base"); } } class Derived extends Base { public void Print() { System.out.println("Derived"); } } class Main{ public static void DoPrint( Base o ) { o.Print(); } public static void main(String[] args) { Base x = new Base(); Base y = new Derived(); Derived z = new Derived(); DoPrint(x); DoPrint(y); DoPrint(z); } } (A) Base Derived Derived (B) Base Base Derived (C) Base Derived Base (D) Compiler Error

Answer: (A) Predicting the first line of output is easy. We create an object of type Base and call DoPrint(). DoPrint calls the print function and we get the first line. DoPrint(y) causes second line of output. Like C++, assigning a derived class reference to a base class reference is allowed in Java. Therefore, the expression Base y = new Derived() is a valid statement in Java. In DoPrint(), o starts referring to the same object as referred by y. Also, unlike C++, functions are virtual by default in Java. So, when we call o.print(), the print() method of Derived class is called due to run time polymorphism present by default in Java.

Consider the following class definition public class Animal { private String type; public Animal(String theType) { type = theType; } public String getType() { return type; } } public class Dog(String theType) { public Dog(String theType) { super(theType); } } Refer to the following declarations and method in a client program Animal d1 = new Animal("poodle"); Animal d2 = new Dog("Shnauzer"); Dog d3 = new Dog("yorkie"); public static void display(Animal a) { System.out.println("This dog is a " + a.getType();) } Which of the following method calls will compile without error? I. display(d1); II display(d2); III display(d3); A. I only B. II only C. III only D. I and II only E. I, II and III

E. All Compile without error. For the ,etjod call display(arg), the compiler checks that the parameter arg is-a Animal., the type in the method's signature. Each of the objects d1,d2,d3 passes the is-a Animal test.

/* Java program to demonstrate whether we can override private method of outer class inside its inner class */ class Outer { private String msg = "GeeksforGeeks"; private void fun() { System.out.println("Outer fun()"); } class Inner extends Outer { private void fun() { System.out.println("Accessing Private Member of Outer: " + msg); } } public static void main(String args[]) { // In order to create instance of Inner class, we // need an Outer class instance. So, first create // Outer class instance and then inner class // instance. Outer o = new Outer(); Inner i = o.new Inner(); // This will call Inner's fun, the purpose of this call // is to show that private members of Outer can // be accessed in Inner. i.fun(); // o.fun() calls Outer's fun (No run-time // polymorphism). o = i; o.fun(); } }

Accessing Private Member of Outer: GeeksforGeeks Outer fun() In Java, methods declared as private can never be overridden, they are in-fact bounded during compile time. An inner class can access private members of its outer class. Inner classes can access private members of its outer class, for example in the following program, fun() of Inner, accesses private data member msg which is fine by the compiler. method fun() has not been overriden. It is so because private methods are bonded during compile time and it is the type of the reference variable - not the type of object that it refers to - that determines what method to be called..

Public is redundant for an interface because...

All the method signatures defined here HAVE to be used in a different class: Methods from an interface HAVE TO BE public to be used!

Which of the following is true about inheritance in Java? 1) Private methods are final. 2) Protected members are accessible within a package and inherited classes outside the package. 3) Protected methods are final. 4) We cannot override private methods. (A) 1, 2 and 4 (B) Only 1 and 2 (C) 1, 2 and 3 (D) 2, 3 and 4

Answer: (A)

Predict the output of following Java Program // filename Main.java class Grandparent { public void Print() { System.out.println("Grandparent's Print()"); } } class Parent extends Grandparent { public void Print() { System.out.println("Parent's Print()"); } } class Child extends Parent { public void Print() { super.super.Print(); System.out.println("Child's Print()"); } } public class Main { public static void main(String[] args) { Child c = new Child(); c.Print(); } } (A) Compiler Error in super.super.Print() (B) Grandparent's Print() Parent's Print() Child's Print() (C) Runtime Error

Answer: (A) Explanation: In Java, it is not allowed to do super.super. We can only access Grandparent's members using Parent.

class Base { public static void show() { System.out.println("Base::show() called"); } } class Derived extends Base { public static void show() { System.out.println("Derived::show() called"); } } class Main { public static void main(String[] args) { Base b = new Derived();; b.show(); } } (A) Base::show() called (B) Derived::show() called (C) Compiler Error

Answer: (A) Explanation: Like C++, when a function is static, runtime polymorphism doesn't happen.

class Base { final public void show() { System.out.println("Base::show() called"); } } class Derived extends Base { public void show() { System.out.println("Derived::show() called"); } } class Main { public static void main(String[] args) { Base b = new Derived();; b.show(); } } (A) Base::show() called (B) Derived::show() called (C) Compiler Error (D) Runtime Error

Answer: (C) Explanation: Final methods cannot be overridden. See the compiler error here.

Predict the output of following program. Note that fun() is public in base and private in derived. class Base { public void foo() { System.out.println("Base"); } } class Derived extends Base { private void foo() { System.out.println("Derived"); } } public class Main { public static void main(String args[]) { Base b = new Derived(); b.foo(); } } (A) Base (B) Derived (C) Compiler Error (D) Runtime Error

Answer: (C) Explanation: It is compiler error to give more restrictive access to a derived class function which overrides a base class function.

Remember: you don't actually create the full methods in an interface. You simply...

Define the methods: You just create the method "signature" here (otherwise known as method "stubs"): public interface ITelephone { public void powerOn(); public void dial(int phoneNumber); public void answer(); public boolean callPhone(int phoneNumber); public boolean isRinging(); } The code itself is DEFINED in the actual class. What we have defined here now is the CONTRACT with the PARAMETERS that makes sure that the method signature will not change!

What's bottom-up development

Its an object-oriented approach to writing the program which tests the simplest classes first. In bottom-up approach first designing, beginning from the base level to the abstract level is done.

Dynamic binding or late binding

Making a run-time decision about which instance method to call is known as dynamic or late binding.

Can a subclass override static methods of the superclass ?

No

Can a subclass redefine a public method of the superclass as private?

No

Can private methods in a superclass be overriden in a subclass?

No

Can a subclass directly access the private members of its superclass ?

No the subclass must accessor or mutator methods to access the private members of its superclass.

Can constructors be inherited from the superclass?

No, constructors are never inherited. Be sure to provide at least 1 constructor for a subclass. If a subclass has no constructor, the default constructor with no parameters for the superclass is generated. If the superclass does not have a default constructor but only has a constructor with parameters, a compile-time error will occur.

Static Binding (Early Binding)

The compiler selects the correct overloaded method at compile time by comparing the methods' signatures

What does a constructor do ?

The primary job of a constructor is to provide reasonable values to a class's attributes. (properties).A constructor initialises the private instance variables.

class Base { public void fun() { System.out.println("Base fun"); } } class Derived extends Base { public void fun() { // overrides the Base's fun() System.out.println("Derived fun"); } public static void main(String[] args) { Base obj = new Derived(); obj.fun(); } } Whats the Output ?

The program prints "Derived fun". The Base class reference 'obj' refers to a derived class object (see expression "Base obj = new Derived()"). When fun() is called on obj, the call is made according to the type of referred object, not according to the reference.

Can a public method in a superclass be overriden in a subclass ?

Yes, any public method in a superclass can be overrridden in a subclass - by defining a method with the same return type and signature (name and parameter types) Sometimes the code for overriding a method includes a call to the superclass method. This is called partial overriding. eg. in the subclass public void computerGrade() { super.computerGrade(); if (getTestAverage() >= 90) setGrade("PAss with distinction"); }

A 'non-parameter' constructor is said to have no ____________, and provides _____________ initial values for an object

arguments, reasonable

A 'non-parameter' constructor is often called a __________ constructor

default

information hiding

is restriction of access to private data and methods in a class. The practice of hiding the details of a module with the goal of controlling access to the details of the module

A constructor creates a(n) ______________ of a class

object

The compiler makes a decision about which constructor to use by using it's ___________ _____________

parameter signature

True or false: A constructor is a method

true

True or false: It is common for a class to have multiple constructors

true


Ensembles d'études connexes

Distributive Property and Combining Like Terms

View Set