Memory :
package com.Immutable;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public final class DOB {
private final String Fname;
private final String Lname;
private final Calendar myCalendar = new GregorianCalendar(2013, 04, 10);
private final Date date = myCalendar.getTime();
public DOB(String fname, String lname) {
super();
this.Fname = fname;
this.Lname = lname;
//this.date = date;
}
public String getFname() {
return Fname;
}
public String getLname() {
return Lname;
}
/*public Date getDate() {
return date;
}*/
public Date getDate() {
return new Date(date.getTime());
}
}
Immutable class User defined
package com.example.demo.immutable;
public class ImmutableClass {
private int id;
private String name;
private NoImmutableClass noImmutableClass;
public ImmutableClass(int id, String name, NoImmutableClass noImmutableClass) {
this.id = id;
this.name = name;
this.noImmutableClass = noImmutableClass;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
/*
* public NoImmutableClass getNoImmutableClass() { return noImmutableClass; }
*/
/* Making non changeable class, once assign value, it cannot be change */
public NoImmutableClass getNoImmutableClass() {
return new NoImmutableClass(name, name);
}
@Override
public String toString() {
return "ImmutableClass [id=" + id + ", name=" + name + ", noImmutableClass=" + noImmutableClass + "]";
}
}
equals
method of StringBuffer
is not overridden from Object
, so it is just reference equality,
i.e., the same as using ==
. I suspect the reason for this is that StringBuffer
is modifiable, and overriding equals
is mostly useful for value-like
classes that you might want to use as keys (though lists also have an
overridden equals
and StringBuffer
is kind of a list, so this is a bit inconsistent).1. System.out.println(sb1 == sb2);
StringBuffer's equals method returns true
only when a StringBuffer object is compared with itself. It returns false when
compared with any other StringBuffer, even if the two contain the same characters.This is because "==" checks the reference equality and since both sb1 and sb2 are different object references, so the output in this case is "false"
Still if you want to check if the content is equal in these two StringBuffer Objects, you can use this:
sb1.toString().equals(sb2.toString())
2. System.out.println(sb1.equals(sb2));
This is giving output as "false"
because .equals() method has not been overridden in the StringBuffer Class. So
it is using the .equals() method from its parent "Object" class. In
the object class .equals() has been written to check the reference equality.Note that sb3.equals(sb4) will return "true" in case of String. Because .equals() method has been overridden in String class to check and match the content of two different Strings.
StringBuffer does not override the Object.equals method, so it is not
performing a string comparison. Instead it is performing a direct object
comparison. Your conditional may as well be if(s1==s2). If you want to
compare the strings you'll need to turn the buffers into strings first. |
Myth about the file name and class name in Java
/*****
File name: Trial.java ******/ public class Geeks { public static void main(String[]
args) { System.out.println("Hello
world"); } } |
javac Trial.java
Trial.java:9: error: class Geeks is public, should be
declared in a file named Geeks.java
public class Geeks
^
1 error
/*****
File name: Trial.java ******/ class Geeks { public static void main(String[]
args) { System.out.println("Hello
world"); } } |
Step 1: javac Trial.java
Step 2: java Geeks
public.
/***
File name: Trial.java ***/ class ForGeeks { public static void main(String[] args){ System.out.println("For
Geeks class"); } } class GeeksTest { public static void main(String[] args){ System.out.println("Geeks
Test class"); } } |
Since each class has separate main() stub they can be tested individually.
When java ForGeeks is executed the output is For Geeks class.
When java GeeksTest is executed the output is Geeks Test class.
Local Variables
Example
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.pupAge();
}
}
Puppy age is: 7
Access
Modifier
|
within class
|
within package
|
outside package by
subclass only
|
outside package
|
Private
|
Y
|
N
|
N
|
N
|
Default
|
Y
|
Y
|
N
|
N
|
Protected
|
Y
|
Y
|
Y
|
N
|
Public
|
Y
|
Y
|
Y
|
Y
|
NOTE :- The default modifier is more restrictive
than protected. That is why there is compile time error.
package com.Accessifier_Content;
public class Protected_Class_Test {
protected int number = 100;
protected void name(){
System.out.println("Ali");
}
}
------------------------
package com.Accessifier;
import com.Accessifier_Content.*;
public class Protected_Class_Test_Main extends Protected_Class_Test {
int num = super.number;
public static void main(String[] args) {
Protected_Class_Test_Main pctm = new Protected_Class_Test_Main();
int num = pctm.number;
}
}
--------------------------------------
package com.Accessifier_Content;
public class Protected_Class_Test_Main_2 {
public static void main(String[] args) {
Protected_Class_Test pct = new Protected_Class_Test();
int num = pct.number;
pct.name();
}
}
--------------------------------------------------------------------------------
package com.Accessifier_Content;
public class Car_3 {
int number_Default =100;
public int number_Defalt_Public = 200;
protected int number_Default_Protected = 300;
}
package com.Accessifier;
import com.Accessifier_Content.Car_3;
public class TestDefault_Extends extends Car_3{
public int speedTesT(){
return super.number_Default_Protected;
}
public static void main(String[] args) {
TestDefault_Extends tde = new TestDefault_Extends();
int number_Main = tde.number_Default_Protected;
Car_3 car_3 = new Car_3();
//car_3.number_Defalt_P
}
}
|
The Object class provides
many methods. They are as follows:
|
Method
|
Description
|
public final Class getClass()
|
returns the Class class object of this
object. The Class class can further be used to get the metadata of this
class.
|
public int hashCode()
|
returns the hashcode number for this
object.
|
public boolean equals(Object obj)
|
compares the given object to this
object.
|
protected Object clone() throws
CloneNotSupportedException
|
creates and returns the exact copy
(clone)
of this object.
|
public String toString()
|
returns the string representation of
this
object.
|
public final void notify()
|
wakes up single thread, waiting on this
object's monitor.
|
public final void notifyAll()
|
wakes up all the threads, waiting on
this
object's monitor.
|
public final void wait(long
timeout)throws InterruptedException
|
causes the current thread to wait for
the
specified milliseconds, until another
thread notifies (invokes notify() or
notifyAll()
method).
|
public final void wait(long timeout,int
nanos)throws InterruptedException
|
causes the current thread to wait for
the specified milliseconds and
nanoseconds,
until another thread notifies (invokes
notify()
or notifyAll() method).
|
public final void wait()throws
InterruptedException
|
causes the current thread to wait, until
another thread notifies (invokes
notify() or
notifyAll() method).
|
protected void finalize()throws
Throwable
|
is invoked by the garbage collector
before
object is being garbage collected.
|
- Whatever the parent class
has, is by default available to the child. Hence by using child reference,
we can call both parent and child class methods.
- Whatever the child class
has, by default is not available to parent, hence on the parent class reference we can only call parent class
methods but not child specific methods.
- Parent class reference can
be used to hold child class objects , but by using that reference we can
call only parent class methods but not child specific methods.
- We can't use child class
reference to hold parent class objects
IS-A Relationship:
In object oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example House is a Building. But Building is not a House.
It is key point to note that you can easily identify the IS-A relationship. Wherever you see an extends keyword or implements keyword in a class declaration, then this class is said to have IS-A relationship.
package com.Inheritance;
class Person{
}
class Employee extends Person{
}
class Teacher extends Person{
}
public class Teacher_Math extends Teacher {
public static void main(String args[]){
Teacher_Math teacher_Math = new Teacher_Math();
Teacher teacher = new Teacher();
Employee employee = new Employee();
Person person = new Person();
System.out.println(employee instanceof Person);
System.out.println(teacher instanceof Person);
System.out.println(teacher_Math instanceof Teacher);
System.out.println(teacher_Math instanceof Person);
}
}
Composition(HAS-A) simply mean use of instance variables that are references to other objects. For example: Maruti has Engine, or House has Bathroom.
Let’s understand these concepts with example of Car class.
- package relationships;
- class Car {
-
- // Methods implementation and class/Instance members
-
- private String color;
- private int maxSpeed;
- public void carInfo(){
-
- System.out.println("Car Color= "+color + " Max Speed= " + maxSpeed);
- }
- public void setColor(String color) {
-
- this.color = color;
-
- }
- public void setMaxSpeed(int maxSpeed) {
-
- this.maxSpeed = maxSpeed;
-
- }
- }
- class Maruti extends Car{
-
- //Maruti extends Car and thus inherits all methods from Car (except final and static)
-
- //Maruti can also define all its specific functionality
-
- public void MarutiStartDemo(){
-
- Engine MarutiEngine = new Engine();
-
- MarutiEngine.start();
-
- }
-
- }
- package relationships;
-
- public class Engine {
-
- public void start(){
-
- System.out.println("Engine Started:");
-
- }
- public void stop(){
-
- System.out.println("Engine Stopped:");
-
- }
-
- }
- package relationships;
-
- public class RelationsDemo {
-
- public static void main(String[] args) {
-
- Maruti myMaruti = new Maruti();
-
- myMaruti.setColor("RED");
-
- myMaruti.setMaxSpeed(180);
- myMaruti.carInfo();
- myMaruti.MarutiStartDemo();
-
- }
- }
publicclassExample{
publicvoid sayHi {
system.out.println("Hi");
}
Example(){}
}
publicclassSubClassextendsExample{
}
SubClass
class
automatically inherits the sayHi
method
found in the parent class. However, the constructor Example()
is
not inherited by the SubClass
.
1
Difference
between Association, Composition and Aggregation in Java, UML and Object
Oriented Programming
Composition : Since Engine is part-of Car, relationship between them is Composition. Here is how they are implemented between Java classes.
publicclassCar {
//final will make sure engine is initialized
privatefinal Engine engine;
publicCar(){
engine = new Engine();
}
}
classEngine {
private String type;
}
Aggregation : Since Organization has Person as employees, relationship between them is Aggregation. Here is how they look like in terms of Java classes
publicclassOrganization {
private List employees;
}
publicclassPerson {
private String name;
}
For example a car class can inherit some properties from a General vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy.
class Box {
double width;
double height;
double depth;
Box() {
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
void getVolume() {
System.out.println("Volume is : " + width * height * depth);
}
}
public class MatchBox extends Box {
double weight;
MatchBox() {
}
MatchBox(double w, double h, double d, double m) {
super(w, h, d);
weight = m;
}
public static void main(String args[]) {
MatchBox mb1 = new MatchBox(10, 10, 10, 10);
mb1.getVolume();
System.out.println("width of MatchBox 1 is " + mb1.width);
System.out.println("height of MatchBox 1 is " + mb1.height);
System.out.println("depth of MatchBox 1 is " + mb1.depth);
System.out.println("weight of MatchBox 1 is " + mb1.weight);
}
}
OutputVolume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0
------------------------------------------------------------------------------------------------
composition
-------------------------------------------------------------------------------------------------------------------
Download MatchBox.java
What is not possible using java class Inheritance?
1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.
4. A subclass can extend only one superclass
class Vehicle {
-------------------------------------------------------------------
package com.Accessifier_Content;
public class Car_3 {
int number_Default =100;
public int number_Defalt_Public = 200;
}
---
package com.Accessifier;
import com.Accessifier_Content.Car_3;
public static void main(String[] args) {
TestDefault_Extends tde = new TestDefault_Extends();
int number_Main = tde.number_Defalt;
}
}
----------------------------------------------------------------
// Instance fields
int noOfTyres; // no of tyres
private boolean accessories; // check if accessorees present or not
protected String brand; // Brand of the car
// Static fields
private static int counter; // No of Vehicle objects created
// Constructor
Vehicle() {
System.out.println("Constructor of the Super class called");
noOfTyres = 5;
accessories = true;
brand = "X";
counter++;
}
// Instance methods
public void switchOn() {
accessories = true;
}
public void switchOff() {
accessories = false;
}
public boolean isPresent() {
return accessories;
}
private void getBrand() {
System.out.println("Vehicle Brand: " + brand);
}
// Static methods
public static void getNoOfVehicles() {
System.out.println("Number of Vehicles: " + counter);
}
}
class Car extends Vehicle {
private int carNo = 10;
public void printCarInfo() {
System.out.println("Car number: " + carNo);
System.out.println("No of Tyres: " + noOfTyres); // Inherited.
// System.out.println("accessories: " + accessories); // Not Inherited.
System.out.println("accessories: " + isPresent()); // Inherited.
// System.out.println("Brand: " + getBrand()); // Not Inherited.
System.out.println("Brand: " + brand); // Inherited.
// System.out.println("Counter: " + counter); // Not Inherited.
getNoOfVehicles(); // Inherited.
}
}
public class VehicleDetails { // (3)
public static void main(String[] args) {
new Car().printCarInfo();
}
}
OutputConstructor of the Super class called
Car number: 10
No of Tyres: 5
accessories: true
Brand: X
Number of Vehicles: 1
-----------------------------------------------------------------------------------------------------
DownloadVehicleDetails.java
this and super keywords
The two keywords,
this and super to help you explicitly name the field or method that you want.
Using this and super you have full control on whether to call a method or field
present in the same class or to call from the immediate superclass. This
keyword is used as a reference to the current object which is an instance of
the current class. The keyword super also references the current object, but as
an instance of the current class’s super class.The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference. Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.
class Counter {
int i = 0;
Counter increment() {
i++;
return this;
}
void print() {
System.out.println("i = " + i);
}
}
public class CounterDemo extends Counter {
public static void main(String[] args) {
Counter x = new Counter();
x.increment().increment().increment().print();
}
}
Outputi : 3
Copy Constructor in Java Example
class Rectangle
{
int length;
int breadth;
//constructor to initialize length and bredth of rectang of rectangle
Rectangle(int l, int b)
{
length = l;
breadth= b;
}
//copy constructor
Rectangle(Rectangle obj)
{
System.out.println("Copy Constructor Invoked");
length = obj.length;
breadth= obj.breadth;
}
//method to calcuate area of rectangle
int area()
{
return (length * breadth);
}
}
//class to create Rectangle object and calculate area
class CopyConstructor
{
public static void main(String[] args)
{
Rectangle firstRect = new Rectangle(5,6);
Rectangle secondRect= new Rectangle(firstRect);
System.out.println("Area of First Rectangle : "+ firstRect.area());
System .out.println("Area of First Second Rectangle : "+ secondRect.area());
}
}
------------------------------------------------------------------------------------------------------------------
Object Cloning in Java
Why use clone() method ?
Advantage of Object cloning
Example of clone() method (Object cloning)
Output:101 amit
101 amit
-----------------------------------------------------------------------------------------------------------------------
Shallow Copy
package com.Clone;
class A {
int i;
int j;
}
public class CloningTest {
public static void main(String[] args) {
A a = new A();
a.i = 10;
a.j = 20;
A b = a;
b.i = 50;
b.j = 60;
System.out.println(a.i);
System.out.println(a.j);
System.out.println("-------------------------");
System.out.println(b.i);
System.out.println(b.j);
}
}
50
60
-------------------------
50
60
package com.example.demo.cloning;
class Cat {
int j = 10;
Cat(int j) {
this.j = j;
}
}
class Dog implements Cloneable {
Cat c;
int i;
Dog(Cat c, int i) {
this.c = c;
this.i = i;
}
public Object clone() throws CloneNotSupportedException {
Cat c1 = new Cat(c.j);
Dog d2 = new Dog(c1, i);
return d2;
}
}
public class DeepCloningDemo {
public static void main(String[] args) throws CloneNotSupportedException {
Cat c = new Cat(20);
Dog d1 = new Dog(c, 10);
System.out.println(d1.i + "----" + d1.c.j);
Dog d2 = (Dog) d1.clone();
d2.i = 888;
d2.c.j = 999;
System.out.println(d2.i + "----" + d2.c.j);
}
}
Overloading vs Overriding in Java
- Overloading happens at
compile-time while Overriding
happens at runtime: The binding of
overloaded method call to its definition has happens at compile-time
however binding of overridden method call to its definition happens at
runtime.
- Static methods can be
overloaded which means a class can have more than one static method of
same name. Static methods cannot be overridden, even if you declare a same
static method in child class it has nothing to do with the same method of
parent class.
- The most basic
difference is that overloading is being done in the same class while for
overriding base and child classes are required. Overriding is all about
giving a specific implementation to the inherited method of parent class.
- Static
binding
is being used for overloaded methods and dynamic
binding
is being used for overridden/overriding methods.
- Performance:
Overloading gives better performance compared to overriding. The reason is
that the binding of overridden methods is being done at runtime.
- private and final
methods can be overloaded but they cannot be overridden. It means a class
can have more than one private/final methods of same name but a child
class cannot override the private/final methods of their base class.
- Return type of method
does not matter in case of method overloading, it can be same or
different. However in case of method overriding the overriding method can
have more specific return type (refer
this).
- Argument list should
be different while doing method overloading. Argument list should be same
in method Overriding.
- In
java, method overloading can't be performed by changing return type of the
method only. Return type can be same or different in
method overloading. But you must have to change the parameter.
Return type must be same or covariant in method overriding.
There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.
If you overload static method in java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.
1.1
Runtime Polymorphism in Java
Runtime
polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
Let's first understand the upcasting before Runtime Polymorphism.
1.1.1
Upcasting
When reference
variable of Parent class refers to the object of Child class, it is known as
upcasting. For example: - class A{}
- class B extends A{}
- A a=new B();//upcasting
Example
of Java Runtime Polymorphism
In this example,
we are creating two classes Bike and Splendar. Splendar class extends Bike
class and overrides its run() method. We are calling the run method by the
reference variable of Parent class. Since it refers to the subclass object and
subclass method overrides the Parent class method, subclass method is invoked
at runtime. Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
- class Bike{
- void run(){System.out.println("running");}
- }
- class Splender extends Bike{
- void run(){System.out.println("running safely with 60km");}
-
- public static void main(String args[]){
- Bike b = new Splender();//upcasting
- b.run();
- }
- }
Output:running safely with 60km.
Real example of Java Runtime Polymorphism
Consider a
scenario, Bank is a class that provides method to get the rate of interest. But,
rate of interest may differ according to banks. For example, SBI, ICICI and
AXIS banks could provide 8%, 7% and 9% rate of interest.Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Method is overridden not the datamembers, so runtime polymorphism
can't be achieved by data members.
|
In the example given below, both the classes have a datamember
speedlimit, we are accessing the datamember by the reference variable of
Parent class which refers to the subclass object. Since we are accessing the
datamember which is not overridden, hence it will access the datamember of
Parent class always.
|
1.1.1.1 Rule: Runtime polymorphism can't
be achieved by data members.
- class Bike{
- int speedlimit=90;
- }
- class Honda3 extends Bike{
- int speedlimit=150;
-
- public static void main(String args[]){
- Bike obj=new Honda3();
- System.out.println(obj.speedlimit);//90
- }
Output:90
1.2
Java Runtime Polymorphism with Multilevel Inheritance
Let's see the
simple example of Runtime Polymorphism with multilevel inheritance.- class Animal{
- void eat(){System.out.println("eating");}
- }
-
- class Dog extends Animal{
- void eat(){System.out.println("eating fruits");}
- }
-
- class BabyDog extends Dog{
- void eat(){System.out.println("drinking milk");}
-
- public static void main(String args[]){
- Animal a1,a2,a3;
- a1=new Animal();
- a2=new Dog();
- a3=new BabyDog();
-
- a1.eat();
- a2.eat();
- a3.eat();
- }
- }
Output: eating
eating fruits
drinking Milk
1.2.1
Try for Output
- class Animal{
- void eat(){System.out.println("animal is eating...");}
- }
-
- class Dog extends Animal{
- void eat(){System.out.println("dog is eating...");}
- }
-
- class BabyDog1 extends Dog{
- public static void main(String args[]){
- Animal a=new BabyDog1();
- a.eat();
- }}
Output: Dog is eating
Since, BabyDog is
not overriding the eat() method, so eat() method of Dog class is invoked.
2
Polymorphism
In Java
2.1
Introduction
Java is an
object-oriented programming language, so polymorphism in Java is the bread and
butter of object-oriented programming in Java. In this tutorial we're going to
find out what polymorphism is, why it is so useful, and then show how to use it
to create elegant programs. This concept is somewhat difficult to put into
practice because it happens to be much more abstract than many of the other
concepts. However, if you can master it, you will become that much better of a
programmer and you will have a much easier time mastering the Java language.
2.2
What is
Polymorphism?
Polymorphism is THE concept to master if you want to
master object-oriented programming. Because Java is an object-oriented
language, it makes sense that you should learn the concepts and power of
polymorphism in Java. Simply put, polymorphism is what allows actions to act differently based on the object performing the action or the object the action is being performed on. Let's just use a super simple, real life example. What is a typical sound that a cat makes? Let's just say it's meow. Let's call this action makeSound() because remember, a method can represent an action. What sound does a dog make? Let's just say a dog goes woof. We can also call this action makeSound(). Let's also just pretend that all animals can makeSound(). Thus, makeSound(), depending on the type of animal, does something different. The action acts differently based on the object.
This concept of polymorphism in Java especially, is actually not hard to understand at all. Oh look, different animals make different sounds, and the same method can be used to make each distinct sound. If you've done the Java inheritance tutorial, you already know how to do this!
One powerful tool for using polymorphic behavior is to use the same method name but in the same class, over and over again to get the desired effects you want. How can we use polymorphism in Java to accomplish this?
2.3
Overloaded
Methods
Let's use our
makeSound() example again. Let's say a dog makes a woof sound, but if the dog
is injured, the dog might make a whimper noise instead. How can we use
makeSound() to produce both sounds? Take a look at this code snippet: NOTE: At this point, if you're not sure you understand the code you see, you REALLY should go back to the Intermediate Tutorials and read the tutorial on Methods In Java. Then you can come back to learn about polymorphism in Java once you have a better understanding of methods.
We can see here that depending on the number of parameters we pass to makeSound(), the dog will make a different sound. But wait! Couldn't we have just used an if statement and make this just one method? Yes, we could have done that and that's probably a better way of programming this for this particular example. What if an outside action causes the difference in dog sound though? Something like this:
If the dog did not have the variable to know it was hurt, you would not be able to write that if statement as easily.
You can overload a method as much as you want as long as the number of parameters are different or the types of parameters are different. You could not do this for example:
This is because those are the same number of parameters AND are the same types of parameters.
2.4
Overridden
Methods
In Java, you can
create a method in a superclass (or parent class), then in a subclass ALSO define
that method. Let's see an example of this using Animal: Now, let's say you could actually create Animals. If you could, then calling makeSound() would call the method defined in the superclass. If you create a specific Dog, calling makeSound() will display "woof". Now let's say you created a specific Cat. In that example, Cat does not have a makeSound() method, so when you call makeSound() on Cat, it calls the method in the superclass Animal and does nothing. Remember, Cat and Dog are subclasses of Animal because they extend Animal.
This behavior is called method overriding, and it is EXTREMELY powerful stuff when it comes to polymorphism in Java. Java will let you do this because its possible more specific types of objects have more specific behaviors for actions. How does Java then know which method to actually call? Java will always pick the object's true type for choosing which method to call, the superclass or the subclass. We will see what true type really means in the next section.
2.5
Dynamic Method
Binding
Do not let the
long name confuse you. This is not that scary of a term! We won't discuss why
this is dynamic, but let's just say that Java decides what method to call
during runtime, or once the program is running. Dynamic method binding is how
Java decides what method to call when it has to decide between the superclass
and the subclass. So, how exactly does it decide? To illustrate this point, we
must first illustrate the concept of true type versus referenced type. Look, we just made a Dog but declared it as an Animal! Normally you would see this:
However, you can also declare a variable by its supertype or abstract type to make it more generic. Let's say you don't know what kind of animal you want:
Notice how the variable is not assigned to anything! We have an animal that has not been instantiate, and it does not equal anything. We can't create just Animals because they are abstract, so we must make a specific kind of animal, which is what we did with the example above by making the Animal be a new Dog.
So, which version of makeSound() would you use if you saw Animal animal = new Dog() ? Would you choose the Animal's version or the Dog's version? The answer is that Java will choose the true type, and the true type is the object that actually gets created. In this example, what we are really creating is a Dog, even though we are referencing the variable as an Animal.
Why in the world wouldn't we just do Dog dog = new Dog() ? The answer is that by using abstraction, you can actually group many different types of objects together. Let's see how we can use this concept for storing objects:
We could not do the above if the Cat objects and Dog objects were made the traditional way and not by referencing them as Animals.
It is very important you do not flip the reference and the true type! You could not do this:
First of all, in our example, you cannot create Animal objects because they are abstract. Let's assume you could though. This is still illegal because a specific type cannot be the reference of a more broad type. Think about it this way: A dog is an animal but an animal is not necessarily a dog. The above example is basically saying that an Animal is a Dog, and this is not always true.
Polymorphism in Java allows you to fully control how you group objects together and gives you the power to make them as specific as you want. It is also the crucial part of object-oriented programming that allows you to build hierarchies of objects, objects that have a logical structure that makes sense in the real world. Because of polymorphism, you can create highly sophisticated programs in Java that are easy to read and are well organized. It does not guarantee an awesome organization of your code, but if you're careful it can help you immensely in doing so.
My final advice about polymorphism in Java is to practice! Practice making a bunch of abstract and regular classes. Create your own object structures. Make different objects extend each other. Write the same methods over and over again using different parameters and putting them in the parent classes and subclasses. Then, test out your objects by writing a main class that uses the classes and methods you write in different ways. By doing so, you will be on your way to mastering this highly abstract, highly powerful concept!
If you would like to leave a comment for Polymorphism in Java, please click here to go to the questions/comments page! Or, simply click the appropriate contact link in the sidebar. Thanks!
Encapsulation
2.5.1.1 Advantage of
Encapsulation in java
void setSSN(int ssn)
)and read (for e.g. int getSSN()
) the private data fields then the outside class can access
those private data fields via public methods. This way data can only be
accessed by public methods thus making the private fields and their
implementation hidden for outside classes. That’s why encapsulation is known as data hiding. Lets see
an example to understand this concept better.
2.6
Benefits of Encapsulation:
·
Advantage
of Encapsulation in java
Java – Abstraction
Abstraction is process of hiding the implementation details and showing only the functionality.
Abstraction in java is achieved by using interface and abstract class. Interface give 100% abstraction and abstract class give 0-100% abstraction.
What is Abstract class in Java?
A class that is declared as abstract is known as abstract class.
Syntax:
abstract class <class-name>{}
An abstract class is something which is incomplete and you cannot create instance of abstract class.
If you want to use it you need to make it complete or concrete by extending it.
What is Abstract method in Java?
A method that is declare as abstract and does not have implementation is known as abstract method.
If you define abstract method than class must be abstract.
Syntax:
abstract return_type method_name ();
An abstract method in Java doesn't have body, it’s just a declaration. In order to use abstract method you need to override that method in Subclass.
Example 1 :( Without abstract method)
Example 2: (with abstract method)
When do you use abstraction?
When you know something needs to be there but not sure how exactly it should look like.
Advantages of Abstraction
By using abstraction, we can separate the things that can be grouped to another type.
Frequently changing properties and methods can be grouped to a separate type so that the main type need not undergo changes. This adds strength to the OOAD principle -"Code should be open for Extension but closed for Modification".
Simplifies the representation of the domain models.
Summary:
- Use abstraction if you know something needs to be in class but implementation of that varies.
- In Java you cannot create instance of abstract class , its compiler error.
- abstract is a keyword in java.
- A class automatically becomes abstract class when any of its method declared as abstract.
- abstract method doesn't have method body.
- Variable cannot be made abstract, its only behavior or methods which would be abstract.
- If a class extends an abstract class or interface it has to provide implementation to all its abstract method to be a concrete class. Alternatively this class can also be abstract.
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.
Creating Arrays
Syntax
arrayRefVar = new dataType[arraySize];
Check if an array has
duplicate numbers
We discuss three different implementations of this function with various time and space complexities.
Time complexity: O(n2)
Space complexity: O(1)
The following is the C++ function which implements this approach.
bool checkDuplicates( int array[], int n)
{
int i,j;
for( i = 0; i < n; i++ )
{
for( j = i+1; j < n; j++ )
{
if( array[i] == array[j] )
return true;
}
}
return false;
}
Space complexity: O(1)
The following is the C++ function which implements this approach.
bool checkDuplicates( int array[], int n)
{
std::sort( array, array+n);
int i;
for( i = 0; i < n-1; i++)
{
if( array[i] == array[i+1] )
return true;
}
return false;
}
Space complexity: O(n)
The following is the Java function which implements this approach.
public static boolean checkDuplicates(int [] array)
{
HashSet<Integer> hSet = new HashSet<Integer>();
for( int i = 0; i < array.length; i++ )
{
if( !hSet.add(array[i]) )
return true;
}
return false;
}
public static void main(String[] args) {
int[] arr1 = new int[] { 10, 3, 4, 20};
int[] arr2 = new int[] { 10, 20, 30 };
//convert arr1 to java.util.Set
Set<Integer> set1 = new HashSet<Integer>();
for (int i : arr1) {
set1.add(i);
}
// print the duplicates
for (int i : arr2) {
if (set1.contains(i)) {
System.out.println(i); // print 10 20
}
}
}
1.1.1
16) How to synchronize List, Set and Map elements?
public static
List synchronizedList(List l){}
|
public static
Set synchronizedSet(Set s){}
|
public static
SortedSet synchronizedSortedSet(SortedSet s){}
|
public static
Map synchronizedMap(Map m){}
|
public static
SortedMap synchronizedSortedMap(SortedMap m){}
|
1.1.2
17) What is the advantage of generic collection?
1.1.3
18) What is hash-collision in Hashtable and how it is
handled in Java?
1.1.4
19) What is the Dictionary class?
- Data growth - Internally,
both the ArrayList and Vector hold onto their contents using an Array.
When an element is inserted into an ArrayList or a Vector, the object will
need to expand its internal array if it runs out of room. A Vector
defaults to doubling the size of its array, while the ArrayList increases
its array size by 50 percent.
- Performance - Since vector
is thread-safe , the performance is slower than ArrayList.
1.1.5
1) What is the difference between ArrayList and Vector?
No.
|
ArrayList
|
Vector
|
1)
|
ArrayList is not
synchronized.
|
Vector is
synchronized.
|
2)
|
ArrayList is
not a legacy class.
|
Vector is a
legacy class.
|
3)
|
ArrayList
increases its size by 50% of the array size.
|
Vector
increases its size by
doubling the
array size.
|
- Implement Comparable
interface for the Employee class and override the compareTo(Object obj)
method in which compare the employeeID
- Now call Collections.sort()
method and pass the list as an argument.
- 1) Since Comparable
interface cannot be implemented, create Comparator and override the
compare(Object obj, Object obj1) method.
- 2) Call Collections.sort()
on the list and pass comparator as an argument.
- ArrayList : It is a resizable array
implementation.The size of the ArrayList can be increased dynamically also
operations like add,remove and get can be formed once the object is
created. It also ensures that the data is retrieved in the manner it was
stored. The ArrayList is not thread-safe.
- Vector: It is thread-safe implementation of
ArrayList. The methods are wrapped around a synchronized block.
- LinkedList: the LinkedList implements Queue interface
too and provide FIFO (First In First Out) operation for add operation. It
is faster than ArrayList if it's mainly used forinsertion and deletion of
elements.
- Once
the array is created elements cannot be added or deleted from it. But with
ArrayList the elements can be added and deleted at runtime.
- ArrayList
is one dimensional but array can be multidimensional.
- Array
can contain objects of a single data type or class. ArrayList if not used
with generic can contain objects of different classes
1.1.1
2) What is the difference between ArrayList and
LinkedList?
No.
|
ArrayList
|
LinkedList
|
1)
|
ArrayList
uses a dynamic array.
|
LinkedList
uses doubly linked list.
|
2)
|
ArrayList is
not efficient for manipulation because a lot of shifting is required.
|
LinkedList is
efficient for manipulation.
|
3)
|
ArrayList is
better to store and fetch data.
|
LinkedList is
better to manipulate data.
|
- Adding
new elements is pretty fast for either type of list. Inserting element to
n location in arraylist and to first location in linkedlist takes O(1).
- For
the ArrayList, doing random lookup using "get" is fast, but for
LinkedList O(n), it's slow. It's slow because there's no efficient way to
index into the middle of a linked list. Linkedlist lookup always start
from 1st location.
- When
removing elements, using ArrayList is slow. This is because all remaining
elements in the underlying array of Object instances must be shifted down
for each remove operation. But LinkedList is fast, because deletion can be
done simply by changing a couple of links.
- If later on code needs to be changed from ArrayList
to Vector then only at the declaration place we can do that.
- The most important one – If a function is
declared such that it takes list. E.g void showDetails(List list);
When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible.
1. Thread -Safe :
ConcurrentHashMap is thread-safe that is the code can be accessed by single thread at a time .
while HashMap is not thread-safe .
2. Synchronization Method :
HashMap can be synchronized by using
synchronizedMap(HashMap) method . By using this
method we get a HashMap object which is equivalent
to the HashTable object . So every modification is performed
on Map is locked on Map object.
ConcurrentHashMap synchronizes or locks on the certain portion of the Map . To optimize
the performance of ConcurrentHashMap , Map is divided into different partitions depending
upon the Concurrency level . So that we do not need to synchronize the whole Map Object.
3. Null Key
ConcurrentHashMap does not allow NULL values . So the key can not be null in
ConcurrentHashMap .While In HashMap there can only be one null key .
4. Performance
In multiple threaded environment HashMap is usually faster than ConcurrentHashMap . As
only single thread can access the certain portion of the Map and thus reducing the performance .
While in HashMap any number of threads can access the code at the same time .
- SortedSet - It is an interface which
extends Set. A the name suggest, the interface allows the data to be
iterated in the ascending order or sorted on the basis of Comparator or
Comparable interface. All elements inserted into the interface must
implement Comparable or Comparator interface.
- TreeSet - It is the implementation of SortedSet
interface. This implementation provides guaranteed log(n) time cost for
the basic operations (add, remove and contains). The class is not
synchronized.
- HashSet: This class implements the
Set interface, backed by a hash table (actually a HashMap instance). It
makes no guarantees as to the iteration order of the set; in particular,
it does not guarantee that the order will remain constant over time. This
class permits the null element. This class offers constant time
performance for the basic operations (add, remove, contains and size),
assuming the hash function disperses the elements properly among the
buckets.
HashSet is based on hashMap and can contain null element.
No comments:
Post a Comment