Unit 4 Notes
Unit 4 Notes
Inheritance – results from deriving new classes from existing classes Root Class –
all java classes are derived from the java.lang.Object class
GeometricObject1
GeometricObject ` Superclass
-color:
-color:String
String (object) Parent Class
-fllled: boolean (color) Base Class
-dateCreated:
-fllled: booleanjava.util.Date
-dateCreated: java.util.Date
+GeometricObject( )
+getColor( ): String
+setColor(color: String ): void
+GeometricObject( )
+isFilled( ): boolean
+setFilled(filled: boolean): void
+getColor( ): String
+getDateCreated( ): java.util.Date
+toString( ): String
+setColor(color: String ): void
+isFilled( ): boolean Subclass Child
+setFilled(filled: boolean): void Class Derived
Class
+getDateCreated( ): java.util.Date Extended Class
+toString( ): String
Circle4 Rectangle1
-radius: double -width: double
-height: double
+Circle( )
+Circle(radius: double) +Rectangle( )
+getRadius( ): double +Rectangle(width: double, height: double)
+setRadius(radius: double): void +getWidth( ): double
+getArea( ): double +setWidth(width: double): void
+getParimeter( ): double +getHeight( ): double
+getDiameter( ): double +setHeight(height: double): void
+printCircle( ): void +getArea( ): double
+getPerimeter( ): double
A child class inherits all accessible data fields and methods from its parent class! A child
class does not inherit the constructors of the parent class!
The child class may also add uniquely new data fields and methods!
1. Implementation
a. GeometricObject1.java
b. Circle4.java
public Circle4( ) { }
public Circle4(double radius ) { this.radius = radius; }
}
c. Rectangle1.java
public Rectangle1( ) { }
public Rectangle1(double width, double height )
{
this width = width; this
height = height;
}
d. TestCircleRectangle.java
Remark: Inheritance is used to model is-a relationships; e.g., an apple is a fruit! For a class
B to extend a class A, class B should contain more detailed information than
class A.
A subclass and a superclass must have an is-a relationship
Remark: C++ allows inheritance from multiple classes; i.e., it supports multiple
inheritance.
Remark: Java does not allow inheritance from multiple classes; a Java class may inherit
directly only from one superclass, i.e., the restriction is known as single
inheritance. If the extends keyword is used to define a subclass, it allows only
one parent class. Multiple inheritance in java is achieved by the use of interfaces.
2. Constructor Chaining
A child class inherits all accessible data fields and methods from its parent class,
BUT the child class does not inherit the constructors of the parent class!
public Faculty( )
{
public Employee( )
{
this(“(2) Employee’s overloaded constructor invoked”); System.out.println(“(3)
Employee’s no-arg constructor invoked”);
}
class Person
{
public Person( )
{
System.out.println(“(1) Person’s no-arg constructor invoked”);
}
}
Best Practices
{
private String color = “white”; private
boolean filled;
}
a. Rules for Overridding Inherited Methods
private data fields in a superclass are not accessible outside of that class, hence they
cannot be used directly by a subclass; they can be accessed &/or mutated by public
accessor &/or mutators defined in the superclass
if a method defined in a subclass is private in its superclass, the two methods are
completely unrelated
a static method can be inherited, but a static method cannot be overridden remember that
static methods are class methods
{ {
public static void main(String [ ] args) public static void main(String [ ] args)
{ {
a.p(10) invokes class A
A a = new A( ); a.p(10); A a = new A(a.p(10) invokes class B method;
); a.p(10);
method; hence prints 10
hence prints nothing
} }
} }
overloads
overrides
class B class B
{ {
public void p(int i){ } public void p(int i){ }
} }
4. Object Class & Methods
o Override the equals( ) method to test whether two distinct objects have
the same content, e.g.,
INSTANCEOF OPERATOR
public boolean equals(Object o)
{ o instanceof Circle
returns true if o is an instance of Circle
if (o instanceof Circle)
{
return radius == ((Circle)o).radius;
Do not use (Circle o) as the argument
} when overriding the equals( ) method,
i.e., do not use the signature
else return false; public boolean equals( Circle o)
} see page 355 #10.12
Comparison Operators/Methods
o “==” operator is used to compare primitive data type values
o “==” operator is also used to compare whether two reference variables
refer to the same object (where arrays may be considered to be objects)
o The modified “equals( )” method can be used to determine whether two
objects have the same contents
class base
{
.....
.....
}
class derive extends base
{
.....
.....
}
class Person {
void teach() {
System.out.println("Teaching subjects");
} }
class CheckForInheritance {
public static void main(String args[]) {
Person s1 = new Students();
s1.teach();
s1.listen();
}
}
In this type of inheritance, a derived class gets created from another derived
class and can have any number of levels.
class Teacher {
void teach() {
System.out.println("Teaching subject");
}
}
class Student extends Teacher {
void listen() {
System.out.println("Listening");
}
}
class homeTution extends Student
{ void explains() {
System.out.println("Does
homework");
}
}
class CheckForInheritance {
public static void main(String argu[])
{ homeTution h = new
himeTution(); h.explains();
d.teach();
d.listen();
}
}
In this type of inheritance, there are more than 1 derived classes which
get created from one single base class.
class
Teacher {
void teach()
{
System.out.println("Teaching subject");
}
}
Let us imagine a situation where there are three classes: A, B and C. The
C class inherits A and B classes. In case, class A and class B have a method
with same name and type and as a programmer, you have to call
that
method from child class's (C) object, there-there will be ambiguity as which method will be
if the object o were to invoke a method, i.e., o.p( ); then the JVM searches for the
method p( ) in the classes in the order C1, C2, C3, C4, java.lang.Object
System.out.println(x.toString( ));
}
}
The call for the execution of the method m(new GraduateStudent( ));
results in a the invocation of the toString( ) method; the JVM starts a search of the inheritance chain
starting with the GraduateStudent class for an implementation of the toString( ) method.
The Student class yields such an implementation which results in the output of the string “Student”.
The call for the execution of the method m(new Student( )); results in the invocation of its
toString( ) method and the output of the second string “Student”.
The call for the execution of the method m(new Person( )); results in the invocation of its
toString( ) method and the output of the string “Person”.
The call for the execution of the method m(new Object( )); results in the invocation of the
java.lang.Object’s toString( ) method and the output of a string similar to
“java.lang.object@AD23F5”.
A reference variable’s declared type determines which method is matched at compile time;
i.e., the compiler uses the parameter type, the number & order of parameters to determine
the matching method.
For a method defined in several subclasses, the JVM dynamically binds the
implementation of a method at runtime decided by the actual class of the object
referenced by the variable.
Recall that polymorphism refers to the use a variable of a supertype to refer to an object
of a subtype; the implementation is known as generic programming.
If a methods parameter type is a superclass, then an object of any of the subclasses
may be passed to the method via that parameter type.
a. Implicit Casting
Object o = new Student( ); m(
o ); equivalent m( new Student( ));
statements
An instance of Student is automatically an instance of Object
b. Explicit Casting
Student b = o; compilation error !
An instance of Object is not necessarily an instance of Student
Student b = (Student) o;
c. Up Casting
Casting an instance of a subclass to a variable of a superclass is always possible; implicit
casting may be used.
d. Down Casting
Casting an instance of a superclass to a variable of a subclass: must use explicit
casting & object cast must be an instance of the subclass
e. instanceof Operator
Object o = new Circle( );
if( o instanceof Circle )
}
The declared type determines which method to match at compile time;
“o.getDiameter( );” would cause a compile error since Object does not contain a
“getDiameter( )” method.
To call an overloaded method in Java, it is must use the type and/or the
number of arguments to determine which version of the overloaded
method to actually call.
The overloaded methods may have varied return types and the return
type single-handedly is insufficient to make out two versions of a
method.
As and when Java compiler encounters a call to an overloaded method,
it simply executes the version of the method whose parameters match
the arguments used in the call.
It permits the user to obtain compile time polymorphism with name
method name.
An overloaded method is able to throw different kinds of exceptions.
A method which is overloaded can contain different access modifiers.
Overloading method's argument lists might differ in:
class Mltply {
Argument list: The argument list at the time of overriding method need
to be same as that of the method of the parent class. The data types of
the arguments along with their sequence must have to be preserved as it
is in the overriding method.
Access Modifier: The Access Modifier present in the overriding method
(method of subclass) cannot be more restrictive than that of an
overridden method of the parent class.
The private, static and final methods can't be overridden as they are
local to the class.
Any method which is overriding is able to throw any unchecked
exceptions, in spite of whether the overridden method usually method
of parent class might throw an exception or not.
//method overriding
class parent {
public void work() {
System.out.println("Parent is under retirement from work.");
}
}
class child extends parent {
public void work() {
System.out.println("Child has a job");
System.out.println(" He is doing it well");
}
public static void main(String argu[]) {
child c1 = new child();
c1.work();
} }
One major advantage of method overriding is that a class can give its own specific
execution to an inherited method without having the modification in the parent
class (base class).
We can use super keyword to access the data member or field of parent class.
It is used if parent class and child class have same fields.
1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
The super keyword can also be used to invoke the parent class constructor.
Let's see a simple example:
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }}
1. class Person{
2. int id;
3. String name;
4. Person(int id,String name){
5. this.id=id;
6. this.name=name;
7. }
8. }
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constructor
13. this.salary=salary;
14. }
15. void display(){System.out.println(id+" "+name+" "+salary);}
16. }
17. class TestSuper5{
18. public static void main(String[] args){
19. Emp e1=new Emp(1,"ankit",45000f);
20. e1.display();
21. }}
If a class has multiple methods having same name but different in parameters,
it is known as Method Overloading.
In this example, we have created two methods, first add() method performs
addition of two numbers and second add method performs addition of three
numbers.
In this example, we are creating static methods so that we don't need to create
instance for calling methods.
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
In this example, we have created two methods that differs in data type. The
first add method receives two integer arguments and second add method
receives two double arguments.
1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
If subclass (child class) has the same method as declared in the parent class, it
is known as method overriding in java.
ABSTRACTION
Abstraction in Java
Another way, it shows only important things to the user and hides the internal
details for example sending sms, you just type the text and send the message. You
don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
1. abstract class A{ }
abstract method
A method that is declared as abstract and does not have implementation is
known as abstract method.
In this example, Bike the abstract class that contains only one abstract
method run. It implementation is provided by the Honda class.
There are mainly three reasons to use interface. They are given below.
In this example, Printable interface has only one method, its implementation
is provided in the A class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Differences between abstract class and interface that are given below.
1. interface A{
2. void a(); void b();
3. void c(); void d();
4. }
5. abstract class B implements A{
6. public void c(){System.out.println("I am c");}
7. }
8. class M extends B{
9. public void a(){System.out.println("I am a");}
10. public void b(){System.out.println("I am b");}
11. public void d(){System.out.println("I am d");}
12. }
13. class Test5{
14. public static void main(String args[]){
15. A a=new M();
16. a.a();
17. a.b();
18. a.c();
19. a.d();
20. }}