
Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the informatio...
Everything is in this blog
Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the informatio...
In the previous chapter, we talked about super classes and sub classes. If a class inherits a method from its super class, then there ...
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent cl...
Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot be instantiated. All other fu...
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction. Encapsulat...
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interfa...
Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, inte...
Replace these every slider sentences with your featured post descriptions.Go to Blogger edit html and find these sentences.Now replace these with your own descriptions.
Replace these every slider sentences with your featured post descriptions.Go to Blogger edit html and find these sentences.Now replace these with your own descriptions.
Replace these every slider sentences with your featured post descriptions.Go to Blogger edit html and find these sentences.Now replace these with your own descriptions.
public class Animal{ } public class Mammal extends Animal{ } public class Reptile extends Animal{ } public class Dog extends Mammal{ }Now, based on the above example, In Object Oriented terms, the following are true:
public class Dog extends Mammal{ public static void main(String args[]){ Animal a = new Animal(); Mammal m = new Mammal(); Dog d = new Dog(); System.out.println(m instanceof Animal); System.out.println(d instanceof Mammal); System.out.println(d instanceof Animal); } }This would produce the following result:
true true trueSince we have a good understanding of the extends keyword let us look into how the implements keyword is used to get the IS-A relationship.
public interface Animal {} public class Mammal implements Animal{ } public class Dog extends Mammal{ }
interface Animal{} class Mammal implements Animal{} public class Dog extends Mammal{ public static void main(String args[]){ Mammal m = new Mammal(); Dog d = new Dog(); System.out.println(m instanceof Animal); System.out.println(d instanceof Mammal); System.out.println(d instanceof Animal); } }This would produce the following result:
true true true
public class Vehicle{} public class Speed{} public class Van extends Vehicle{ private Speed sp; }This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class., which makes it possible to reuse the Speed class in multiple applications.
public class extends Animal, Mammal{}However, a class can implement one or more interfaces. This has made Java get rid of the impossibility of multiple inheritance.
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 a.move();// runs the method in Animal class b.move();//Runs the method in Dog class } }This would produce the following result:
Animals can move Dogs can walk and runIn the above example, you can see that the even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object.
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 void bark(){ System.out.println("Dogs can bark"); } } 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 a.move();// runs the method in Animal class b.move();//Runs the method in Dog class b.bark(); } }This would produce the following result:
TestDog.java:30: cannot find symbol symbol : method bark() location: class Animal b.bark(); ^This program will throw a compile time error since b's reference type Animal doesn't have a method by the name of bark.
class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ super.move(); // invokes the super class method System.out.println("Dogs can walk and run"); } } public class TestDog{ public static void main(String args[]){ Animal b = new Dog(); // Animal reference but Dog object b.move(); //Runs the method in Dog class } }This would produce the following result:
Animals can move Dogs can walk and run
public interface Vegetarian{} public class Animal{} public class Deer extends Animal implements Vegetarian{}Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above example:
Deer d = new Deer(); Animal a = d; Vegetarian v = d; Object o = d;All the reference variables d,a,v,o refer to the same Deer object in the heap.
/* File name : Employee.java */ public class Employee { private String name; private String address; private int number; public Employee(String name, String address, int number) { System.out.println("Constructing an Employee"); this.name = name; this.address = address; this.number = number; } public void mailCheck() { System.out.println("Mailing a check to " + this.name + " " + this.address); } public String toString() { return name + " " + address + " " + number; } public String getName() { return name; } public String getAddress() { return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber() { return number; } }Now suppose we extend Employee class as follows:
/* File name : Salary.java */ public class Salary extends Employee { private double salary; //Annual salary public Salary(String name, String address, int number, double salary) { super(name, address, number); setSalary(salary); } public void mailCheck() { System.out.println("Within mailCheck of Salary class "); System.out.println("Mailing check to " + getName() + " with salary " + salary); } public double getSalary() { return salary; } public void setSalary(double newSalary) { if(newSalary >= 0.0) { salary = newSalary; } } public double computePay() { System.out.println("Computing salary pay for " + getName()); return salary/52; } }Now, you study the following program carefully and try to determine its output:
/* File name : VirtualDemo.java */ public class VirtualDemo { public static void main(String [] args) { Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00); Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00); System.out.println("Call mailCheck using Salary reference --"); s.mailCheck(); System.out.println("\n Call mailCheck using Employee reference--"); e.mailCheck(); } }This would produce the following result:
Constructing an Employee Constructing an Employee Call mailCheck using Salary reference -- Within mailCheck of Salary class Mailing check to Mohd Mohtashim with salary 3600.0 Call mailCheck using Employee reference-- Within mailCheck of Salary class Mailing check to John Adams with salary 2400.0Here, we instantiate two Salary objects . one using a Salary reference s, and the other using an Employee reference e.
/* File name : Employee.java */ public abstract class Employee { private String name; private String address; private int number; public Employee(String name, String address, int number) { System.out.println("Constructing an Employee"); this.name = name; this.address = address; this.number = number; } public double computePay() { System.out.println("Inside Employee computePay"); return 0.0; } public void mailCheck() { System.out.println("Mailing a check to " + this.name + " " + this.address); } public String toString() { return name + " " + address + " " + number; } public String getName() { return name; } public String getAddress() { return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber() { return number; } }Notice that nothing is different in this Employee class. The class is now abstract, but it still has three fields, seven methods, and one constructor.
/* File name : AbstractDemo.java */ public class AbstractDemo { public static void main(String [] args) { /* Following is not allowed and would raise error */ Employee e = new Employee("George W.", "Houston, TX", 43); System.out.println("\n Call mailCheck using Employee reference--"); e.mailCheck(); } }When you would compile above class then you would get the following error:
Employee.java:46: Employee is abstract; cannot be instantiated Employee e = new Employee("George W.", "Houston, TX", 43); ^ 1 error
/* File name : Salary.java */ public class Salary extends Employee { private double salary; //Annual salary public Salary(String name, String address, int number, double salary) { super(name, address, number); setSalary(salary); } public void mailCheck() { System.out.println("Within mailCheck of Salary class "); System.out.println("Mailing check to " + getName() + " with salary " + salary); } public double getSalary() { return salary; } public void setSalary(double newSalary) { if(newSalary >= 0.0) { salary = newSalary; } } public double computePay() { System.out.println("Computing salary pay for " + getName()); return salary/52; } }Here, we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salary object will inherit the three fields and seven methods from Employee.
/* File name : AbstractDemo.java */ public class AbstractDemo { public static void main(String [] args) { Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00); Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00); System.out.println("Call mailCheck using Salary reference --"); s.mailCheck(); System.out.println("\n Call mailCheck using Employee reference--"); e.mailCheck(); } }This would produce the following result:
Constructing an Employee Constructing an Employee Call mailCheck using Salary reference -- Within mailCheck of Salary class Mailing check to Mohd Mohtashim with salary 3600.0 Call mailCheck using Employee reference-- Within mailCheck of Salary class Mailing check to John Adams with salary 2400.
public abstract class Employee { private String name; private String address; private int number; public abstract double computePay(); //Remainder of class definition }Declaring a method as abstract has two results:
/* File name : Salary.java */ public class Salary extends Employee { private double salary; // Annual salary public double computePay() { System.out.println("Computing salary pay for " + getName()); return salary/52; } //Remainder of class definition }
/* File name : EncapTest.java */ public class EncapTest{ private String name; private String idNum; private int age; public int getAge(){ return age; } public String getName(){ return name; } public String getIdNum(){ return idNum; } public void setAge( int newAge){ age = newAge; } public void setName(String newName){ name = newName; } public void setIdNum( String newId){ idNum = newId; } }The public methods are the access points to this class' fields from the outside java world. Normally, these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters.
/* File name : RunEncap.java */ public class RunEncap{ public static void main(String args[]){ EncapTest encap = new EncapTest(); encap.setName("James"); encap.setAge(20); encap.setIdNum("12343ms"); System.out.print("Name : " + encap.getName()+ " Age : "+ encap.getAge()); } }This would produce the following result:
Name : James Age : 20
/* File name : NameOfInterface.java */ import java.lang.*; //Any number of import statements public interface NameOfInterface { //Any number of final, static fields //Any number of abstract method declarations\ }Interfaces have the following properties:
/* File name : Animal.java */ interface Animal { public void eat(); public void travel(); }
/* File name : MammalInt.java */ public class MammalInt implements Animal{ public void eat(){ System.out.println("Mammal eats"); } public void travel(){ System.out.println("Mammal travels"); } public int noOfLegs(){ return 0; } public static void main(String args[]){ MammalInt m = new MammalInt(); m.eat(); m.travel(); } }This would produce the following result:
Mammal eats Mammal travelsWhen overriding methods defined in interfaces there are several rules to be followed:
//Filename: Sports.java public interface Sports { public void setHomeTeam(String name); public void setVisitingTeam(String name); } //Filename: Football.java public interface Football extends Sports { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); } //Filename: Hockey.java public interface Hockey extends Sports { public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); }The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports.
public interface Hockey extends Sports, Event
package java.util; public interface EventListener {}An interface with no methods in it is referred to as a tagging interface. There are two basic design purposes of tagging interfaces:
/* File name : Animal.java */ package animals; interface Animal { public void eat(); public void travel(); }Now, put an implementation in the same package animals:
package animals; /* File name : MammalInt.java */ public class MammalInt implements Animal{ public void eat(){ System.out.println("Mammal eats"); } public void travel(){ System.out.println("Mammal travels"); } public int noOfLegs(){ return 0; } public static void main(String args[]){ MammalInt m = new MammalInt(); m.eat(); m.travel(); } }Now, you compile these two files and put them in a sub-directory called animals and try to run as follows:
$ mkdir animals $ cp Animal.class MammalInt.class animals $ java animals/MammalInt Mammal eats Mammal travels
package payroll; public class Boss { public void payEmployee(Employee e) { e.mailCheck(); } }What happens if Boss is not in the payroll package? The Boss class must then use one of the following techniques for referring to a class in a different package.
payroll.Employee
import payroll.*;
import payroll.Employee;Note: A class file can contain any number of import statements. The import statements must appear after the package statement and before the class declaration.
// File Name : Car.java package vehicle; public class Car { // Class implementation. }Now, put the source file in a directory whose name reflects the name of the package to which the class belongs:
....\vehicle\Car.javaNow, the qualified class name and pathname would be as below:
....\com\apple\computers\Dell.javaAt the time of compilation, the compiler creates a different output file for each class, interface and enumeration defined in it. The base name of the output file is the name of the type, and its extension is .class
// File Name: Dell.java package com.apple.computers; public class Dell{ } class Ups{ }Now, compile this file as follows using -d option:
$javac -d . Dell.javaThis would put compiled files as follows:
.\com\apple\computers\Dell.class .\com\apple\computers\Ups.classYou can import all the classes or interfaces defined in \com\apple\computers\ as follows:
import com.apple.computers.*;Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as:
By doing this, it is possible to give the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses.\sources\com\apple\computers\Dell.java \classes\com\apple\computers\Dell.class