Abstract class is a class that has no instances.
An abstract class is written with the expectation that its concrete subclasses will add to its structure and behaviour, typically by implementing its abstract operations
Sunday, June 17, 2012
What is Polymorphism?
Polymorphism literally means taking more than one form.
Inheritance, Overloading and Overriding are used to achieve Polymorphism in java
The abiltiy to define more than one function with the same name is called Polymorphism.
Inheritance, Overloading and Overriding are used to achieve Polymorphism in java
The abiltiy to define more than one function with the same name is called Polymorphism.
In java,c++ there are two type of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding)
Polymorphism is briefly described as "one interface, many implementations."
When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time.
Overriding occurs when a class method has the same name and signature as a method in parent class.
Overloading occurs when several methods have same names with
Overloading is determined at the compile time.
Different method signature and different number or type of parameters.
Same method signature but different number of parameters.
Same method signature and same number of parameters but of different type
class BookDetails{
String title;
setBook(String title){ }
}
class ScienceBook extends BookDetails{
setBook(String title){} //overriding
setBook(String title, String publisher,float price){ } //overloading
}
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java).
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods).
In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).
Method overloading
Method overriding through inheritance
Method overriding through the Java interface
The overriding method cannot have a more restrictive access modifier than the method being overridden
(Ex: You can’t override a method marked public and make it protected).
You cannot override a method marked final
You cannot override a method marked static
method overloading would be an example of static polymorphism
whereas overriding would be an example of dynamic polymorphism.
Dynamic, or late, binding occurs when a method is defined for several classes in a family, but the actual code for the method is not attached, or bound, until execution time.This gives support for overriding...
Static binding occurs when a method is defined with the same name but with different headers and implementations. The actual code for the method is attached, or bound, at compile time. Static binding is used to support overloaded methods in Java.
http://www.coderanch.com/t/379004/java/java/static-polymorphism-dynamic-polymorphism
Compile time polymorphism and the other is run time polymorphism.
Compile time polymorphism is method overloading.
Runtime time polymorphism is done using inheritance and interface.
- static polymorphism vs dynamic polymorphism
method overloading would be an example of static polymorphism
whereas overriding would be an example of dynamic polymorphism.
Dynamic, or late, binding occurs when a method is defined for several classes in a family, but the actual code for the method is not attached, or bound, until execution time.This gives support for overriding...
Static binding occurs when a method is defined with the same name but with different headers and implementations. The actual code for the method is attached, or bound, at compile time. Static binding is used to support overloaded methods in Java.
http://www.coderanch.com/t/379004/java/java/static-polymorphism-dynamic-polymorphism
What is Inheritance?
Inheritance is a relationship among classes, wherein one class shares the structure or behaviour defined in another class
Inheritance is the property which allows a Child class to inherit some properties from its parent class.
In Java this is achieved by using extends keyword.
Only properties with access modifier public and protected can be accessed in child class.
The two most common reasons to use inheritance are:
To promote code reuse
To use polymorphism
What is Encapsulation?
Encapsulation is the process of compartmentalising the elements of an abtraction that defines the structure and behaviour
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.
Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods.
If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class.
For this reason, encapsulation is also referred to as data hiding.
If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class.
For this reason, encapsulation is also referred to as data hiding.
The encapsulation is achieved by combining the methods and attribute into a class.
Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate.
What is abstraction?
Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects
Abstraction refers to the act of representing essential features without including the background details or explanations.
Abstraction is way of converting real world objects in terms of class.
Abstraction refers to the act of representing essential features without including the background details or explanations.
What are the core OOP’s concepts?
- ChatGPT
2. Interface
Definition: An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields. The methods in interfaces are abstract by default.
Purpose:
Define Contracts: Interfaces define a contract that implementing classes must follow.
Multiple Inheritance: Interfaces allow a class to implement multiple interfaces, overcoming the limitation of single inheritance in Java.
Example in Java:
// Interface
interface Drawable {
void draw();
}
// Class implementing the interface
class Rectangle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}
class Test {
public static void main(String[] args) {
Drawable myRectangle = new Rectangle();
myRectangle.draw(); // Outputs: Drawing a rectangle
}
}
In this example, Drawable is an interface with an abstract method draw(). The Rectangle class implements the Drawable interface and provides its own implementation of draw(). Interfaces define a contract that the Rectangle class adheres to.
1. Abstraction
Definition: Abstraction is the concept of hiding the complex implementation details and showing only the necessary features of an object. It focuses on what an object does rather than how it does it.
Purpose:
Simplify Complex Systems: By focusing on essential characteristics, abstraction simplifies interaction with complex systems.
Define Common Interface: Allows you to define a common interface for different implementations.
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void makeSound();
// Regular method
public void sleep() {
System.out.println("This animal sleeps");
}
}
// Subclass providing specific implementation
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
class Test {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Outputs: Bark
myDog.sleep(); // Outputs: This animal sleeps
}
}
In this example, Animal is an abstract class with an abstract method makeSound(). The Dog class provides a specific implementation of makeSound(). Abstraction allows us to use the Animal class as a common interface without knowing the details of how makeSound() is implemented.
1. Encapsulation
Definition: Encapsulation is the concept of wrapping data (attributes) and methods (functions) that operate on the data into a single unit, usually a class. This means hiding the internal state of an object and requiring all interactions to be performed through an object’s methods.
Purpose:
Protection: It protects an object’s internal state from unintended or harmful modifications.
Controlled Access: By providing public methods (getters and setters), encapsulation allows controlled access to the internal data.
Flexibility: Changes to the internal implementation of a class can be made with minimal impact on other parts of the code.
Example in Java:
public class Person {
private String name; // private attribute
// Constructor
public Person(String name) {
this.name = name;
}
// Public method to access private attribute
public String getName() {
return name;
}
// Public method to modify private attribute
public void setName(String name) {
this.name = name;
}
}
2. Polymorphism
Definition: Polymorphism allows objects to be treated as instances of their parent class rather than their actual class. The most common use of polymorphism is method overriding, where a subclass provides a specific implementation of a method that is already defined in its superclass.
Purpose:
Flexibility: Allows objects of different classes to be treated through a common interface.
Method Overriding: Enables a subclass to provide a specific implementation of a method that is already defined in its superclass.
Example in Java:
class Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
public class Test {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.makeSound(); // Outputs: Bark
myCat.makeSound(); // Outputs: Meow
}
}
3. Inheritance
Definition: Inheritance is a mechanism where one class (subclass or derived class) inherits attributes and methods from another class (superclass or base class). This promotes code reusability and establishes a natural hierarchy between classes.
Purpose:
Reusability: Allows a subclass to reuse code from the superclass, reducing redundancy.
Hierarchy: Establishes a natural hierarchical relationship between classes.
Extensibility: Facilitates the creation of new classes based on existing ones, adding or modifying functionality as needed.
Example in Java:
class Animal {
public void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("Dog barks");
}
}
public class Test {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method
myDog.bark(); // Subclass-specific method
}
}
Summary:
Encapsulation: Bundles data and methods, restricting direct access to some of the object's components.
Polymorphism: Allows objects to be treated as instances of their parent class, enabling method overriding and flexibility.
Inheritance: Enables a new class to inherit attributes and methods from an existing class, fostering code reuse and hierarchy
- 1. Encapsulation
- Definition: Encapsulation is the concept of wrapping data (attributes) and methods (functions) that operate on the data into a single unit, usually a class. This means hiding the internal state of an object and requiring all interactions to be performed through an object’s methods.
- Purpose:
- Protection: It protects an object’s internal state from unintended or harmful modifications.
- Controlled Access: By providing public methods (getters and setters), encapsulation allows controlled access to the internal data.
- Flexibility: Changes to the internal implementation of a class can be made with minimal impact on other parts of the code.
- Example in Java:
- public class Person {
- private String name; // private attribute
- // Constructor
- public Person(String name) {
- this.name = name;
- }
- // Public method to access private attribute
- public String getName() {
- return name;
- }
- // Public method to modify private attribute
- public void setName(String name) {
- this.name = name;
- }
- }
- 2. Polymorphism
- Definition: Polymorphism allows objects to be treated as instances of their parent class rather than their actual class. The most common use of polymorphism is method overriding, where a subclass provides a specific implementation of a method that is already defined in its superclass.
- Purpose:
- Flexibility: Allows objects of different classes to be treated through a common interface.
- Method Overriding: Enables a subclass to provide a specific implementation of a method that is already defined in its superclass.
- Example in Java:
- class Animal {
- public void makeSound() {
- System.out.println("Some sound");
- }
- }
- class Dog extends Animal {
- @Override
- public void makeSound() {
- System.out.println("Bark");
- }
- }
- class Cat extends Animal {
- @Override
- public void makeSound() {
- System.out.println("Meow");
- }
- }
- public class Test {
- public static void main(String[] args) {
- Animal myDog = new Dog();
- Animal myCat = new Cat();
- myDog.makeSound(); // Outputs: Bark
- myCat.makeSound(); // Outputs: Meow
- }
- }
- 3. Inheritance
- Definition: Inheritance is a mechanism where one class (subclass or derived class) inherits attributes and methods from another class (superclass or base class). This promotes code reusability and establishes a natural hierarchy between classes.
- Purpose:
- Reusability: Allows a subclass to reuse code from the superclass, reducing redundancy.
- Hierarchy: Establishes a natural hierarchical relationship between classes.
- Extensibility: Facilitates the creation of new classes based on existing ones, adding or modifying functionality as needed.
- Example in Java:
- class Animal {
- public void eat() {
- System.out.println("This animal eats food");
- }
- }
- class Dog extends Animal {
- public void bark() {
- System.out.println("Dog barks");
- }
- }
- public class Test {
- public static void main(String[] args) {
- Dog myDog = new Dog();
- myDog.eat(); // Inherited method
- myDog.bark(); // Subclass-specific method
- }
- }
- Summary:
- Encapsulation: Bundles data and methods, restricting direct access to some of the object's components.
- Polymorphism: Allows objects to be treated as instances of their parent class, enabling method overriding and flexibility.
- Inheritance: Enables a new class to inherit attributes and methods from an existing class, fostering code reuse and hierarchy
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
Polymorphism, Inheritance and Encapsulation
Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to
make once and have effect in all relevant places
Explain the Polymorphism principle. Explain the different forms of Polymorphism.
Polymorphism in simple terms means one name many forms.
Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface
method overloading is the primary way polymorphism is implemented in Java
overloaded methods:
appear in the same class or a subclass
have the same name but,
have different parameter lists, and,
can have different return types
an example of an overloaded method is print() in the java.io.PrintStream class
public void print(boolean b)
public void print(char c)
public void print(char[] s)
public void print(float f)
public void print(double d)
public void print(int i)
public void print(long l)
public void print(Object obj)
public void print(String s)
Overriding methods
appear in subclasses
have the same name as a superclass method
have the same parameter list as a superclass method
have the same return type as as a superclass method
the access modifier for the overriding method may not be more restrictive than the access modifier of the superclass method
Explain Encapsulation, Polymorphism and Inheritance.
http://www.youtube.com/watch?v=QzX7REqciPY
Polymorphism - comes unders Behaviour->Compile time/Runtime -> enables the varying behaviour of the operations depending upon the type of the object(runtime entity).
http://www.linkedin.com/groups/what-is-difference-between-dynamic-70526.S.217712129?view=&srchtype=discussedNews&gid=70526&item=217712129&type=member&trk=eml-anet_dig-b_pd-ttl-cn&ut=23CVDF6gnvwlE1
Explain Encapsulation, Polymorphism and Inheritance.
http://www.youtube.com/watch?v=QzX7REqciPY
- Inheritance - comes under Relationship -> Generalization/Specilization -> enables code resuability. But also enables maintanence nightmare of managing classes.
Polymorphism - comes unders Behaviour->Compile time/Runtime -> enables the varying behaviour of the operations depending upon the type of the object(runtime entity).
http://www.linkedin.com/groups/what-is-difference-between-dynamic-70526.S.217712129?view=&srchtype=discussedNews&gid=70526&item=217712129&type=member&trk=eml-anet_dig-b_pd-ttl-cn&ut=23CVDF6gnvwlE1
- Class versus object
A class is a template for objects. A class defines object properties including a valid range of values, and a default value. A class also describes object behavior. An object is a member or an "instance" of a class. An object has a state in which all of its properties have values that you either explicitly define or that are defined by default settings.
https://www.ncl.ucar.edu/Document/HLUs/User_Guide/classes/classoview.shtml#:~:text=A%20class%20defines%20object%20properties,are%20defined%20by%20default%20settings.
- Let's see some real life example of class and object in java to understand the difference well:
Class: Human Object: Man, Woman
Class: Fruit Object: Apple, Banana, Mango, Guava wtc.
Class: Mobile phone Object: iPhone, Samsung, Moto
Class: Food Object: Pizza, Burger, Samosa
https://www.javatpoint.com/difference-between-object-and-class
What is a Class?
Class is a template for a set of objects that share a common structure and a common behaviour.
Decorator (Wrapper) Pattern
- Introducing the Decorator Design Pattern
http://www.youtube.com/watch?v=Xk8durvtiys&feature=channel&list=UL
wrapper classes
using wrapper classes to avoid changing code continuously
- Overview of the Decorator Design Pattern
http://www.youtube.com/watch?v=MI_qyfeRk8c&feature=autoplay&list=ULXk8durvtiys&playnext=1
- Coding the Decorator Design Pattern
http://www.youtube.com/watch?v=HkOdDMePE4Q&feature=autoplay&list=ULMI_qyfeRk8c&playnext=2
- Executing the Decorator Design Pattern
http://www.youtube.com/watch?v=Ra-33SFHq6M&feature=autoplay&list=ULHkOdDMePE4Q&playnext=3
- JAVA: Decorator Design Pattern
http://www.youtube.com/watch?v=9FQVs85fZd8&list=UUUvwlMMaeppKPdtAK8PxO8Q&index=2&feature=plcp
also known as wrapper pattern
extends class functionality by delegation
alternative to extending class functionality by inheritance(subclassing)
- Decorator Pattern
http://www.youtube.com/watch?v=T9kqwyhQP24&feature=related
Structural Design Pattern
attach additional responsibility dynamically
alternative to subclassing through composite and delegation
object level pattern
- Java Design Pattern Decorator with Eclipse
http://www.youtube.com/watch?v=k_uTRC7DO68&feature=related
- Decorator sablonu belirli nesnelerin davranislarini yeni türetilmis siniflar olusturmadan degistirmemizi saglar.
Siniflarin varsayilan kodlarini degistirmeden ek
davranislar kazanmasini saglamak için kullanilir.
Bu sekilde her zaman degisen ihtiyaçlarimiza cevap
verebilecek olan siniflari tasarlayabiliriz.
Örnegin; bir GUI bilesenine kenarliklar(border) eklemek
istiyoruz yada kaydirma çubugu (scrollbars) eklemek
istiyoruz.
Bu nesneden iki yeni nesne türeterek bu islemi
yapabiliriz. Bu sekilde yaparsak her nesne için kenarlik
çizdirmek için kenarlik çizimide yapabilen yeni nesneler
türetmemiz gereklidir. Hepsinde yapilan islem kenarlik
çizmedir, buna ragmen tüm kenarliga ihtiyaci olan
bilesenler için yeni siniflar türetmemiz gerekir.
Bu gibi durumlarda Decorator kullanilir
http://members.comu.edu.tr/msahin/courses/ust_duzey_files/patterns/decorator.pdf
- Decorating Servlet Request Objects
how to apply the Decorator pattern to servlet request objects
how to use the pattern in servlets and lists popular servlet-related projects that use it
http://www.oracle.com/technetwork/articles/entarch/decorators-099517.html
what's the difference between abstract and concrete class?
Concrete class - Provides implementation for all its methods & also for methods from extended abstract classes or implemented interfaces
Abstract class - Does not provide implementation for one or more of its methods
Interface - Does not provide implementation for any of its methods
Read more: http://wiki.answers.com/Q/Difference_between_concrete_class_and_abstract_class_and_interface#ixzz1y2HulwzD
The default class is a concrete class. The class keyword is used to define classes (e.g. in Java).
And usually they are simply referred to as classes (without the adjective concrete). (adjective concrete).
Abstract classes usually have partial or no implementation. On the other hand, concrete classes always have full implementation of its behavior.
Unlike concrete classes, abstract classes cannot be instantiated.
Therefore abstract classes have to be extended in order to make them useful.
Abstract classes may contain abstract methods, but concrete classes can’t.
When an abstract class is extended, all methods (both abstract and concrete) are inherited.
The inherited class can implement any or all the methods.
If all the abstract methods are not implemented, then that class also becomes an abstract class.
Read more: http://www.differencebetween.com/difference-between-abstract-class-and-vs-concrete-class/#ixzz1y2IGPCHk
Java Programming Tutorial - 58 - Abstract and Concrete Classes
http://www.youtube.com/watch?v=TyPNvt6Zg8c
Strategy (Policy) Pattern
- Strategy Class can be an interface or an abstract class
- There are a set of classes which extend abstract class or implement interface
- Switching between these classes changes the behaviour of application
- Using a class which extends or implements strategy class with conditional logic,conditional logic represents the behaviour of application
- This pattern helps add or remove specific behaviour to application without having recode or retest all part of application
- algorithms can be changed at runtime or design time
JAVA: Strategy Design Pattern
http://www.youtube.com/watch?v=x3saJPT4SaE&list=PL028D1E25AAF87B8E&index=2&feature=plpp_video
Introducing the Strategy Design Pattern
http://www.youtube.com/watch?v=9n3gF39-trE
Overview of the Strategy Design Pattern
http://www.youtube.com/watch?v=F1841_llRSw&feature=channel&list=UL
Coding the Strategy Design Pattern
http://www.youtube.com/watch?v=vYByr2u8gqk&feature=autoplay&list=ULF1841_llRSw&playnext=1
Executing the Strategy Design Pattern
http://www.youtube.com/watch?v=mmiWFcjMTLw&feature=autoplay&list=ULvYByr2u8gqk&playnext=2
verbs are objects now
The strategy pattern is a behavioral design pattern that allows you to decide which course of action a program should take, based on a specific context during runtime. You encapsulate two different algorithms inside two classes, and decide at runtime which strategy you want to go with.
http://net.tutsplus.com/articles/general/a-beginners-guide-to-design-patterns/
Iterator Pattern
Intent
Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation
We use iterators quite frequently in everyday life. For example, remote control of TV. We just pick up the TV remote control and start pressing Up and Down or Forward and Back keys to iterate through the channels.
Motivation
Need to traverse different data structures so that algorithms can be defined that are capable of interfacing with each transparently.
Reference:
http://kapilnevatia.blogspot.com/2011/12/iterator-pattern.html
Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation
We use iterators quite frequently in everyday life. For example, remote control of TV. We just pick up the TV remote control and start pressing Up and Down or Forward and Back keys to iterate through the channels.
Motivation
Need to traverse different data structures so that algorithms can be defined that are capable of interfacing with each transparently.
Reference:
http://kapilnevatia.blogspot.com/2011/12/iterator-pattern.html