day5_javaoops_3

Download Report

Transcript day5_javaoops_3

Method Overriding in Java
 Whenever same method name is existing in both base
class and derived class with same types of parameters
or same order of parameters is known as method
Overriding.
 Method must have same name as in the parent class.
 Method must have same parameter as in the parent
class.
class Walking
{
void walk()
{
System.out.println("Man walking fast");
}
}
class Man extends Walking
{
void walk()
{
System.out.println("Man walking slowly");
}
}
class OverridingDemo {
public static void main(String args[]) {
Man obj = new Man();
obj.walk();
}
}
Output :
Man walking slowly
Note:
•Whenever we are calling
overridden
method
using
derived class object reference
the highest priority is given to
current class (derived class).
We can see in the above
example high priority is derived
class.
•super. (super dot) can be used
to call base class overridden
method in the derived class.
super. walk()
Output :
Man walking slowly
Man walking fast
Super Keyword Usage
 It is used inside a sub-class method definition to call a
method defined in the super class.
 super is used to refer immediate parent class instance
variable.
 Only public and protected methods can be called by
the super keyword
 1) super.<variable_name> refers to the variable of
variable of parent class.
2) super() invokes the constructor of immediate parent
class.
3) super.<method_name> refers to the method of
parent class.
Program using super keyword al variable level
class Employee
{
float salary=10000;
}
class HR extends Employee
{
float salary=20000;
void display()
{
System.out.println("Salary: "+super.salary);
//print base class salary
}}
class Supervarible
{
public static void main(String[] args) {
HR obj=new HR();
obj.display(); }
}
We
use
super
keyword
to
distinguish between parent or base
class instance variable and current
or derived class instance variable.
Example of super keyword at method level
class Student
{
void message()
{
System.out.println(“Morning Sir");
}}
class Faculty extends Student
{
void message()
{
System.out.println("Good Morning Students");
}
void display()
{
message();
//will invoke or call current class message() method
super.message();/
/will invoke or call parent class message() method
}
public static void main(String args[])
{
Student s=new Student();
s.display();
}}
Runtime Polymorphism or Dynamic method
dispatch
 Dynamic method dispatch is a mechanism by which a call to an
overridden method is resolved at runtime. This is how java implements
runtime polymorphism.
 When an overridden method is called the type of object which it
referred determines which version of overridden method will be called.
Example
Cricekt.java
Output :
Indoor & outdoor
Outdoor game
Outdoor game
class Game
{
public void type()
{
System.out.println("Indoor & outdoor");
}}
class Cricket extends Game
{
public void type()
{
System.out.println(“Outdoor game");
}
public static void main(String[] args)
{
Game gm = new Game();
Cricket ck = new Cricket();
gm.type();
ck.type();
gm=ck; //gm refers to Cricket object
gm.type(); //calls Cricket's version of type
}}
Abstract class in Java
 In java programming we have two types of classes they are
 Concrete class and
Abstract class
 A concrete class is one which is containing fully defined methods or
implemented method.
 An abstract class is one which is containing some defined method and
some undefined method. In java programming undefined methods are
known as un-Implemented or abstract method.
Important Points about abstract class
and methods
 We cannot instantiate an abstract class. i.e., you are




not allowed to create object of Abstract class.
Abstract method must be in a abstract class.
An abstract class has no use until unless it is extended
by some other class.
Abstract method has no body and always end the
declaration with a semicolon(;).
An abstract class must be extended and in a same way
abstract method must be overridden.
Example of abstract class having constructor, data
member, methods
Interfaces
 Interface is similar to class but not a class which is collection of
public static final variables (constants) and abstract methods.
 The interface is a mechanism to achieve fully abstraction in
java.
 An interface can have methods and variables just like the
class but the methods declared in interface are by default
abstract (only method signature, no body).
 Also, the variables declared in an interface are public, static
& final by default.
 “Its like a checklist” : Class that implements an interface
must implement/define all methods declared in the
interface.
Interface vs Abstract Class
 An Interface is like having a 100% Abstract Class. Interfaces
can not have non abstract Methods while abstract Classes
can. A Class can implement more than one Interface while
it can extend only one Class. As abstract Classes comes in
the hierarchy of Classes, they can extend other Classes
while Interface can only extend Interfaces.
 An abstract class can also have constructors and instance
variables as well. An interface, however, can not provide
any method definitions – it can only provide method
headings. Any class that implements the interface is
responsible
for
providing
the
method
definition/implementation.
When to use abstract class and
interface in Java
 An abstract class is good if you think you will plan on using





inheritance since it provides a common base class implementation to
derived classes.
An abstract class is also good if you want to be able to declare nonpublic members.
If you think you will need to add methods in the future, then an
abstract class is a better choice. Because if you add new method
headings to an interface, then all of the classes that already implement
that interface will have to be changed to implement the new methods.
That can be quite a hassle.
In an interface, all methods must be public.
Interfaces are a good choice when you think that the API will not
change for a while.
Interfaces are also good when you want to have something similar to
multiple inheritance, since you can implement multiple interfaces.
Inheritance - Example
interface Person
{
void run(); // abstract method
}
class A implements Person
{
public void run()
{
System.out.println("Run fast");
}
public static void main(String args[])
{
A obj = new A();
obj.run();
}}
Multiple Inheritance using interface
interface Developer
{
void disp();
}
interface Manager
{
void show();
}
class Employee implements Developer, Manager
{
public void disp()
Developer
Manager
{
System.out.println("Hello Good Morning");
}
public void show()
{
System.out.println("How are you ?");
Employee
}
public static void main(String args[]) {
Employee obj=new Employee();
obj.disp();
obj.show();
}}
Pass By Value
Java uses pass by value to pass arguments to a method.
There are important differences between passing a value of
variables of primitive data types and passing arrays.
 For a parameter of a primitive type value, the actual value
is passed. Changing the value of the local parameter inside
the method does not affect the value of the variable outside
the method.
 For a parameter of an array type, the value of the
parameter contains a reference to an array; this reference is
passed to the method. Any changes to the array that occur
inside the method body will affect the original array that
was passed as the argument.
16
Simple Example
public class Test {
public static void m(int number, int[] numbers) {
number = 1001; // Assign a new value to number
numbers[0] = 5555; // Assign a new value to numbers[0]
}
public static void main(String[] args) {
int x = 1; // x represents an int value
int[] y = new int[10]; // y represents an array of int values
m(x, y); // Invoke m with arguments x and y
System.out.println("x is " + x);
System.out.println("y[0] is " + y[0]);
}
}
17
Does Java pass by value or pass by
reference - Interview Question
 As per Java specification everything in Java is pass by
value whether its primitive value or objects and it does
make sense because Java doesn't support pointers or
pointer arithmetic.
 Answer to this question is simple whenever a method
parameter expect object, reference of that object is passed.
 In reality if you pass object as method parameter in Java it
passes "value of reference" or in simple term object
reference or handle to Object in Java. Here reference term
is entirely different than reference term used in C and C+
which directly points to memory address of variable and
subject to pointer arithmetic
Example-passing object
public class ObjPass {
private int value;
public static void increment(ObjPass a)
{
System.out.println(a);
a.value++;
}
public static void main(String args[])
{
ObjPass p = new ObjPass();
p.value = 5;
System.out.println("Before:" + p.value);
increment(p);
System.out.println("After: " + p.value);
System.out.println(p);
}}
Here we pass exactly is a handle of an
object, and in the called method a new
handle created and pointed to the same
object. From the example above you can
see that both p and a refer to the same
object.
class Car
{
String model; //instance variable
Car() {
//constructor to initialize
model="Maruthi";
System.out.println("Car Model is:"+model);
}
void disp(Car m) {
System.out.println("My Car Model is:"+m.model);
}}
public class ObjPass1 {
public static void main(String args[])
{
Car mycar = new Car();
mycar.model="Zen";
mycar.disp(mycar);
}}}
We can access the instance variables of the
object passed inside the called method. It
is good practice to initialize instance
variables of an object before passing
object as parameter to method otherwise
it will take default initial values.
Exercises
 Modify Cricket.java file and insert a ‘chess’ class and print “Indoor
Game” using Dynamic-method-dispatch.
 Write an abstract class Shape with Abstract methods: getArea(),
getPerimeter() and find the area of rectangle.
 Write a program to add two complex numbers using pass by object
 Implement the following using inheritance.
Student
Sports
extends
Exam
implements
extends
Results
class Student
{
// student no and access methods
}
interface Sport
{
// sports grace marks (say 5 marks) and abstract
methods
}
class Exam extends Student
{
// example marks (test1 and test 2 marks) and
access methods
}
class Results extends Exam implements Sport
{
// implementation of abstract methods of Sport
interface
// other methods to compute total marks =
test1+test2+sports_grace_marks;
// other display or final results access methods
}