Java/Inheritance and Polymorphism

From Meshplex

Jump to: navigation, search
Image:Java_programming.jpg
Introduction to Java
Overview of Java
Concepts of Object Oriented Programming
How to Setup Java on your PC
Introduction to Applets
View Applet in a web browser
Data Types, Variables,and Arrays
Operators
Control Statements
Packages, Classes, and Interfaces
Inheritance and Polymorphism
Strings
Recursion
Random Numbers
Exception Handling
Java IO and file Handling
Java Thread and Multithreading
Java Collections
Java Network Programming
Image, Audio, Video
Advanced Java
Generics
AWT
Swing
Regular Expression
JDBC
XML and Java
Inheritence

One of the most effective concepts of OOPs is because it provides the hierarichical classifications and we can create a general class and can be inherited by other classes.

The class which is inherited as defined as “ Super Class” and other classes which inherit the super class is called “Sub class”. A subclass is a specialized version of a Superclass which inherits all of the instance variables and methods defined by the superclass and adds its own, unique elements.

Java provides us a keyword “Extends” which helps the super class to be inherited by the other sub class.

The following program creates a superclass called A and a subclass called B. Notice how the keyword extends is used to create a subclass of A.

public class InheritanceExample {
 
	public static void main(String[] args) {
 
		B b = new B();
 
		// showij is not defined in class B
		// but in class A and still class B
		// is able to call it. This is 
		// called inheritence.
		b.showij();
		b.showk();
		b.sum();
	}
}
 
class A {
	int i = 3;
	int j = 5;
 
	void showij() {
		System.out.println("i and j: " + i + " " + j);
	}
}
 
// Class B is a subclass of Class A.
class B extends A {
	int k = 10;
 
	void showk() {
		System.out.println("k: " + k);
	}
 
	void sum() {
		System.out.println("i+j+k: " + (i + j + k));
	}
}


Polymorphism
Polymorphism is a term which is constituted from two word poly and morphism. Where poly means many and morphism means forms thus it is a concept of OOPS which means many form of an object. This property of objects help them to behave in more than one ways. Polymorphism is about defining a general structure for different types of data. For example we have a general structure called mammal but cat and dog are not similar. They dont make same sound but they make sound.
public class PolymorphismExample {
 
	public static void main(String[] args) {
		Mammal mammal = new Dog();
		mammal.sound();
 
		mammal = new Cat();
		mammal.sound();
	}
}
 
interface Mammal {
 
	public void sound();
}
 
class Dog implements Mammal {
 
	public void sound() {
 
		System.out.println("Dog Barks.");
	}
 
 
}
 
class Cat implements Mammal {
 
	public void sound() {
 
		System.out.println("Cat Mews.");
	}
 
}
Previous Next