Java - Unit 2.1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 36

Unit II

Inheritance
 Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is made
manageable in a hierarchical order.
 The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class,
parent class).

class Super {
.....
}
class Sub extends Super {
.....
}
Example

class Calculation { public class My_Calculation extends Calculation {


int z; public void multiplication(int x, int y) {
z = x * y;
public void addition(int x, int y) { System.out.println("The product of given
z = x + y; numbers:"+z);
System.out.println("The sum of given numbers: “ }
+z);
} public static void main(String args[]) {
int a = 20, b = 10;
public void Subtraction(int x, int y) { My_Calculation demo = new My_Calculation();
z = x - y; demo.addition(a, b);
System.out.println("The difference between given demo.Subtraction(a, b);
numbers:"+z); demo.multiplication(a, b);
} }
} }
Possibilities

 My_Calculation demo1 = new My_Calculation();


- Sub class object. Access Addition, Multiplication and Subtraction

 Calculation demo3 = new My_Calculation();


- Subclass object. Access Addition and Subtraction

 Calculation demo4 = new Calculation();


- Super class object. Access Addition and Subtraction

 My_Calculation demo2 = new Calculation();


Not possible
We can instantiate the class using the superclass reference variable

Calculation demo = new My_Calculation();


demo.addition(a, b);
demo.Subtraction(a, b);

 In case of overridden methods always subclass method will be executed unless super
is invoked.
 All other methods defined only in sub class cannot be executed
 The reason for this is: In compile time, the check is made on the reference type
(My_Calculation()). However, in the runtime, JVM figures out the object type and would
run the method that belongs to that particular object.
Types of
inheritance
Single level inheritance
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Multilevel Inheritance Example

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
Output:
void bark(){System.out.println("barking...");} weeping...
} barking...
class BabyDog extends Dog{ eating...
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Hierarchical
class Animal{ inheritance
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark()
{System.out.println("barking...");}
}
class Cat extends Animal{ Output:
void meow() meowing...
eating...
{System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
Why not multiple inheritance
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Super

The super keyword is similar to this keyword. Following are the


scenarios where the super keyword is used.

1. super can be used to refer immediate parent class instance


variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class
constructor.
1.super is used to refer immediate parent class
instance variable.
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.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
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.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
Output:
void bark(){System.out.println("barking...");}
void work(){
eating...
super.eat();
barking...
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
3. super is used to invoke parent class
constructor.
The super keyword can also be used to invoke the parent class
constructor. Let's see a simple example:

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}

Output:

animal is created
Access modifier
Modifier Description

declarations are visible only within the


Default
package (package private)

declarations are visible within the class


Private
only

declarations are visible within the


Protected
package or all subclasses

Public declarations are visible everywhere


Default Access Modifier
 If we do not explicitly specify any access modifier for classes, methods, variables, etc,
then by default the default access modifier is considered. For example,

package defaultPackage;
class Logger {
void message(){
System.out.println("This is a message");
}
}

The class is visible to all the classes that belong to


the defaultPackage package.
Private Access Modifier
 When variables and methods are declared private, they cannot be accessed
outside of the class. For example,

class Data {
// private variable
private String name;
}
public class Main {
public static void main(String[] main){
// create an object of Data
Data d = new Data();
// access private variable and field from another class
d.name = "Programiz"; //error
}
}
class Data {
private String name;

// getter method
public String getName() {
return this.name;
}
// setter method
public void setName(String name) {
this.name= name;
}
}
public class Main {
public static void main(String[] main){
Data d = new Data();

// access the private variable using the getter and setter


d.setName("Programiz");
System.out.println(d.getName());
}
Protected Access Modifier
 When methods and data members are declared protected, we can access them within the
same package as well as from subclasses. For example,

class Animal {
// protected method
protected void display() {
System.out.println("I am an animal");
}
}
class Dog extends Animal {
public static void main(String[] args) {
// create an object of Dog class
Dog dog = new Dog();
// access protected method
dog.display();
} }
Abstraction in Java
Abstraction is a process of hiding the implementation details from the user, only the
functionality will be provided to the user. In other words, the user will have the
information on what the object does instead of how it does it.
 Abstract classes may contain abstract methods, i.e., methods without body
( public void get(); ) or normal methods.
 But, if a class has at least one abstract method, then the class must be declared
abstract.
 If a class is declared abstract, it cannot be instantiated.
 To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
 If you inherit an abstract class, you have to provide implementations to all the
abstract methods in it.
 It can have constructors and static methods also.
abstract class Bike{
abstract void run();
void run1(){
System.out.println("running not safely..");}
}

class Honda4 extends Bike{


void run(){
System.out.println(“run running safely");}
void run1(){
System.out.println("run 1 running safely..");}
public static void main(String args[]){
Honda4 obj = new Honda4();
obj.run();
obj.run1();
} }
polymorphism

Polymorphism is the ability of an object to take on many forms. It is


of two types:
 Overloading
With two or more methods having same name but different
arguments
 Overriding
The most common use of polymorphism in OOP occurs when
a parent class reference is used to refer to a child class object
Overloading

Java allows to write more than one method in the same class definition with the same name
For example, two methods in ShoppingCart class can have the name computeCost.

public int computeCost() ;


public int computeCost( int tax ) ;
These two methods could exist in the same class since the parameter list.

The following could not:

a) public int computeCost( int surcharge, boolean addSurcharge ) ;


public int computeCost( int tax, boolean getDiscount ) ;

b) public int computeCost( int tax ) ;


public boolean computeCost( int tax ) ;
Overriding
class Animal {
public void move() {
System.out.println("Animals can move");
} }
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
} }
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
Dog d = new Dog();
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
d.move();
} }
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
} }
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
} }
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
} }
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
Rules
 The argument list should be exactly the same for the overridden
method.
 The return type should be the same.
 Final and private methods are nor overrided.
 The access level cannot be more restrictive than the overridden
method's access level. For example: If the superclass method is
declared public then the overridding method in the sub class cannot
be either private or protected.
 A method declared static cannot be overridden but can be re-declared.
 Constructors cannot be overridden but overloaded.
Garbage Collection
 In java, garbage means unreferenced objects.
 Garbage Collection is process of reclaiming the runtime
unused memory. In other words, it is a way to destroy the
unused objects.
 In java it is performed automatically. So, java provides
better memory management.

 Advantage of Garbage Collection


• It makes java memory efficient because garbage collector
removes the unreferenced objects from heap memory.
• It is automatically done by the garbage collector(a part of
JVM) so we don't need to make extra efforts.
How to unreference an object

• By nulling the reference


• By assigning a reference to another
• By anonymous object etc.
1.By nulling the reference

Employee e=new Employee();


e=null;

2. By assigning a reference to another:

Employee e1=new Employee();


Employee e2=new Employee();
e1=e2;//
now the first object referred by e1 is available for garbage collection

3) By anonymous object:

new Employee();
Methods:
finalize() method
 The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This method
is defined in Object class as:
protected void finalize(){}

gc() method
 The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
public static void gc(){}
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}

Output:
object is garbage collected
object is garbage collected
Interfaces
 It has a collection of abstract methods. A class implements an interface, thereby
inheriting the abstract methods of the interface. interface contains behaviors that
a class implements.
 An interface may also contain constants, static methods but Method bodies exist
only for static methods. An interface can contain any number of methods.
 Unless the class that implements the interface is abstract, all the methods of the
interface need to be defined in class.
 An interface is different from a class in several ways, including −
 You cannot instantiate an interface.
 All of the methods in an interface are abstract and are implicitly public.
 An interface cannot contain instance fields. The only fields that can appear in
an interface must be declared both static and final.
 An interface can extend multiple interfaces.

Example: public interface NameOfInterface {


// Any number of final, static fields
// Any number of abstract method declarations\ }
Example
public class MammalInt implements Animal {

public void eat() {


System.out.println("Mammal eats");
}
interface Animal {
public void travel() {
public void eat();
System.out.println("Mammal travels");
public void travel();
}
}
public int noOfLegs() {
return 0;
}

public static void main(String args[]) {


MammalInt m = new MammalInt();
m.eat();
m.travel();
} }
interface Drawable{
void draw();
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}

//Using interface: by third user


class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
}}
Multiple inheritance
• A class can extend only one class, but implement many interfaces. An
interface can extend another interface, in a similar way as a class can
extend another class.
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
public interface Football extends Sports { Multiple Interfaces is allowed for
public void homeTeamScored(int points); interfaces and so an interface can
extend more than one parent interface.
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
public interface Hockey extends Sports,Football {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}

You might also like