protected Object clone() throws CloneNotSupportedException - this method is used to create a copy of an object of a class which implements Cloneable interface. By default it does field-by-field copy as the Object
class doesn't have any idea in advance about the members of the
particular class whose objects call this method. So, if the class has
only primitive data type members then a completely new copy of the
object will be created and the reference to the new object copy will be
returned. But, if the class contains members of any class type then only
the object references to those members are copied and hence the member
references in both the original object as well as the cloned object
refer to the same object.
Cloneable interface We get CloneNotSupportedException if we try to call the clone() method on an object of a class which doesn't implement the Cloneable interface. This interface is a marker interface and the implementation of this interface simply indicates that the Object.clone() method can be called on the objects of the implementing class.
Example: how cloning works in Java?
Class A {
...
}
A objA = new A();
A objACloned = (A) objA.clone();
Now, objA != objACloned - this boolean expression will always be true as in any case a new object reference will be created for the cloned copy.
objA.getClass() == objACloned.getClass() - this boolean expression will also be always true as both the original object and the cloned object are instances of the same class (A in this case).
Initially, objA.equals(objACloned) will return true, but any changes to any primitive data type member of any of the objects will cause the expression to return false.
It's interesting to note here that any changes to the members of the
object referenced by a member of these objects will not cause the
expression to return false.
Reason being, both the copies are referring to same object as only the
object references get copied and not the object themselves. This type of
copy is called Shallow Copy (Read Next - Deep Copy vs Shallow Copy >> You may browse the links given in that article to go through various aspects of Cloning in Java). This can be understood easily by looking at the following memory diagram:-
Wednesday, June 5, 2013
java basics
java basics
class:
template describes the kind of state and behavior that objects of its type support.
Real time examples:
1)
public class Dog{ String breed; int age; String color; void barking(){
//barking action
} void hungry(){
//hungry action
} void sleeping(){ //sleeping action
} }A class can contain any of the following variable types.
- Local variables . variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
- Instance variables . Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
- Class variables . Class variables are variables declared with in a class, outside any method, with the static keyword.
Object:
At runtime when the Java virtual machine encounters new key will, it will use the appropriate class to make an object which is an instance of that class. That objects will have its own states and have access to all of the behaviors defined in the class from which those created.
State ( instance variable ):
Each object ( instance of a class) will have its own unique set of instance variables as defined in the class. The values assigned to an objects instance variables makes up the objects state.
behavior( methods ):
Methods are where the class logic's are stored . They are where the real work gets done and data gets manipulated.
Now i can give a Real time example for Class, Object, and Object's state & behavior
If we take B.Tech graduation there are different classes exist like CSE, EEE, ECE, MEC
and so on. suppose if we take CSE class for our class example. all the students who
graduated in CSE will have different percentage of knowledge in all the subjects of CSE
and they can do software job, any govt job after completion of their course.
here
i)CSE class considered as an example for class.
i) Every student will act as an object.
ii) Percentage of knowledge in subjects is the state of those student objects
iii)Jobs they can do will act as behavior. In performing their job their subjects knowledge get manipulated.
Some important topics need to be discussed those are
Constructors:
When discussing about classes one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class the java compiler builds a default constructor for that class.Each time a new object is created at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.
Example of a constructor is given below:
public class Employee{
public Employee(){
//code follows
}
public Employee(String designation){
// code follows
}
}
A constructor is a block of code that is called when a new object is created. In the constructor there is typically code to initialize the member variables of the object or to do other things that need to be done when a new object is created.
Creating an Object:
there are mainly three steps involved in creation of java objectthose are
1 . loading
2.Instantiating
3.Intializing
Assume that we have a class with name "student" now we want to create object for it
the statement that will write is
st1: student std;
st2 : std=new student();
in statement one it will cretae a reference with std in the stack and its not the object
in statement 2 when u say actual process starts :
LOADING :
As the student class will exist in the hard disk (secondary storage) it will be loaded into the main memory(RAM)
INSTANTIATING:
Once the loading is done it will allocate the memory for the non static members of the class in the heap.
INITIALIZING:
Once the memory is allocated then the data members will be intialized with default values
provided by JVM.
after completing these 3 steps the address of the object will be stored in the a hash table
along with index . this index will be stored in the reference varaible .
Example:
This example explains how to access instance variables and methods of a class:public class Puppy{ int puppyAge; public Puppy(String name){ // This constructor has one parameter, name. System.out.println("Passed Name is :" + name ); } public void setAge( int age ){ puppyAge = age; } public int getAge( ){ System.out.println("Puppy's age is :" + puppyAge ); return puppyAge; } public static void main(String []args){ /* Object creation */ Puppy myPuppy = new Puppy( "tommy" ); /* Call class method to set puppy's age */ myPuppy.setAge( 2 ); /* Call another class method to get puppy's age */ myPuppy.getAge( ); /* You can access instance variable as follows as well */ System.out.println("Variable Value :" + myPuppy.puppyAge ); } }
If we compile and run the above program then it would produce following result:
Passed Name is :tommy Puppy's age is :2 Variable Value :2
Source file declaration rules:
As the last part of this section lets us now look into the source file declaration rules. These rules are essential when declaring classes, import statements and package statements in a source file.- There can be only one public class per source file.
- A source file can have multiple non public classes.
- The public class name should be the name of the source file as well which should be appended by .java at the end. For example : The class name is . public class Employee{} Then the source file should be as Employee.java.
- If the class is defined inside a package, then the package statement should be the first statement in the source file.
- If import statements are present then they must be written between the package statement and the class declaration. If there are no package statements then the import statement should be the first line in the source file.
- Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file.
Java naming convensions
Standard Java Naming Conventions
The below list outlines the standard Java naming conventions for each identifier type:Packages: Names should be in lowercase. With small projects that only have a few packages it's okay to just give them simple (but meaningful!) names:
package pokeranalyzer
package mycalculator
In software companies and large projects where the packages might be imported into other classes, the names will normally be subdivided. Typically this will start with the company domain before being split into layers or features:
package com.mycompany.utilities
package org.bobscompany.application.userinterface
Classes: Names should be in CamelCase. Try to use nouns because a class is normally representing something in the real world:
class Customer
class Account
Interfaces: Names should be in CamelCase. They tend to have a name that describes an operation that a class can do:
interface Comparable
interface Enumerable
Note that some programmers like to distinguish interfaces by beginning the name with an "I":
interface IComparable
interface IEnumerable
Methods: Names should be in mixed case. Use verbs to describe what the method does:
void calculateTax()
string getSurname()
Variables: Names should be in mixed case. The names should represent what the value of the variable represents:
string firstName
int orderNumber
Only use very short names when the variables are short lived, such as in for loops
Constants: Names should be in uppercase.
static final int DEFAULT_WIDTH
static final int MAX_HEIGHT
Access Specifiers In Java with real time example
Definition :
- Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes, fields and methods in Java.These Specifiers determine whether a field or method in a class, can be used or invoked by another method in another class or sub-class. Access Specifiers can be used to restrict access. Access Specifiers are an integral part of object-oriented programming.
Types Of Access Specifiers :
In java we have four Access Specifiers and they are listed below.
1. public
2. private
3. protected
4. default(no specifier)
We look at these Access Specifiers in more detail.
public specifiers :
Public Specifiers achieves the highest level of accessibility. Classes, methods, and fields declared as public can be accessed from any class in the Java program, whether these classes are in the same package or in another package.
Example :
private specifiers :
Private Specifiers achieves the lowest level of accessibility.private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So, the private access specifier is opposite to the public access specifier. Using Private Specifier we can achieve encapsulation and hide data from the outside world.
Example :
- Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes, fields and methods in Java.These Specifiers determine whether a field or method in a class, can be used or invoked by another method in another class or sub-class. Access Specifiers can be used to restrict access. Access Specifiers are an integral part of object-oriented programming.
Types Of Access Specifiers :
In java we have four Access Specifiers and they are listed below.
1. public
2. private
3. protected
4. default(no specifier)
We look at these Access Specifiers in more detail.
public specifiers :
Public Specifiers achieves the highest level of accessibility. Classes, methods, and fields declared as public can be accessed from any class in the Java program, whether these classes are in the same package or in another package.
Example :
- public class Demo { // public class
- public x, y, size; // public instance variables
- }
private specifiers :
Private Specifiers achieves the lowest level of accessibility.private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So, the private access specifier is opposite to the public access specifier. Using Private Specifier we can achieve encapsulation and hide data from the outside world.
Example :
- public class Demo { // public class
- private double x, y; // private (encapsulated) instance variables
- public set(int x, int y) { // setting values of private fields
- this.x = x;
- this.y = y;
- }
- public get() { // setting values of private fields
- return Point(x, y);
- }
- }
protected specifiers :
Methods and fields declared as protected can only be accessed by the subclasses in other package or any class within the package of the protected members' class. The protected access specifier cannot be applied to class and interfaces.
default(no specifier):
When you don't set access specifier for the element, it will follow the default accessibility level. There is no default specifier keyword. Classes, variables, and methods can be default accessed.Using default specifier we can access class, method, or field which belongs to same package,but not from outside this package.
Example :- class Demo
- {
- int i; (Default)
- }
Real Time Example :
How many ways of creating objects in Java?
Well...
there aren't many different ways I suppose. But from an application
programmer perspective here are the different possible ways of creating
objects in Java:-
- Using new operator - the most commonly used way by far. 'new' is an operator and the only operand it requires is a constructor which will be used for initializting the newly created instance. 'new' operator allocates the memory space and initializes the fields with their default values. Then it executes the code inside the specified constrcutor which normally re-writes the default values of some (or all) fields with the particular values mentioned in the constructor definition.
- Using clone() method - Cloning (Shallow or Deep) makes a new copy of the specified object. It doesn't call the 'new' operator internally. Object.clone() is a native method which translates into instructions for allocating the memory and copying the data. Remember that even if we override the clone() method either to implement Deep Cloning or to make the clone() method as 'public' but then also we keep the line super.clone() inside the overriden definition which ultimately calls Object.clone() method only. You might wonder about what the 'new' operator actually translates into and how this approach is different from that. Okay... we all know that 'new' does three tasks - allocating the memory, initializing the fields with default values, and calling the specified constructor. Now the first task is same in both the approaches and there would probably be the same native allocator being used in both the cases. But in case of Cloning, the allocated memory is not initialized with default values and also no constructor is called in this case. Only a datacopy instruction will be executed which copies the data from the original object to the cloned object. Read more about Cloing in this article - Cloning in Java >>
Java Object oriented programming concepts with real time examples
Java Object oriented programming concepts with real time examples
OOPS Concepts are mainly 4
1.Abstraction
2.Encapsulation
3.Inheritance
4.Polymorphism
Abstraction:-Hiding non-essential features and showing the
essential features
(or)
Hiding unnecessary data from the users details,is called
abstraction.
Real Time example:1.TV Remote Button
in that number format and power buttons and other buttons
there.just we are seeing the buttons,we don't see the
button circuits.i.e buttons circuits and wires all are
hidden.so i think its good example.
Encapsulation:It is a process of binding or wrapping the data and the
codes that operates on the data into a single entity. This
keeps the data safe from outside interface and misuse. One
way to think about encapsulation is as a protective wrapper
that prevents code and data from being arbitrarily accessed
by other code defined outside the wrapper.
Real Time Example:
1.Ink is the important component in pen but it is hiding
by some other material
2.Medical Tablet
i.e one drug is stored in bottom layer and another drug is
stored in Upper layer these two layers are combined in
single Tablet.
Inheritance:The new classes, known as derived classes, take over (or
inherit) attribute and behavior of the pre-existing classes,
which are referred to as base classes (or Parent classes).
It is intended to help reuse existing code with little or no
modification.
Real Time Example:
1. Father and Son Relationship
Polymorphism:Single Form behaving differently in different Situations. A single
function or single operator has different characters in different places.
Real Time Example:
1.A girl plays a role of daughter at home and a manager at
office.
2. Person
Person in Home act is husband/son,
in Office acts Employer.
in Public Good Citizen.
<<<<<<<<<<<<<<<<------------------------->>>>>>>>>>>>>
OOPS Concepts with realtime examples
Abstraction helps to hide the non essential features from the user and makes the application user friendly.
Eg. Take your mobile phone. You are having buttons and know the purpose but no need to understand how it prints number on the screen when it is pressed.
2. Encapsulation
It bundles the code into a single unit which makes the code very easy to handle.
Eg.
Take computer keyboard. All the buttons have been enclosed.
3. Inheritance
It helps to inherit the superclass properties to subclasses.
Eg. Father - Son relationship.
4. Polymorphism
A entity which behaves differntly at different places.
Eg. A person behaves as a good husband in family.
He behaves as a good employee at company.
He also behaves as a good citizen in public.
Monday, May 20, 2013
switch case in jsp
<% switch (tabNavigator)
{
case QUALIFICATION:
%>
<jsp:include page="classmaster.jsp"></jsp:include>
<%
break;
case RACKSHELF:
%>
<jsp:include page="rackshelfmaster.jsp"></jsp:include>
<%
break;
case MEDIA:
%>
<jsp:include page="mediamaster.jsp"></jsp:include>
<%
break;
case MEMBER:
%>
<jsp:include page="membermaster.jsp"></jsp:include>
<%
break;
case PLAN:
%>
<jsp:include page="planmaster.jsp"></jsp:include>
<%
break;
case DEPARTMENT:
%>
<jsp:include page="departmentmaster.jsp"></jsp:include>
<%
break;
case VENDOR:
%>
<jsp:include page="vendormaster.jsp"></jsp:include>
<%
break;
default:
%>
<jsp:include page="index.jsp"></jsp:include>
<%
}
session.removeAttribute("NAVIGATOR_REQUEST");
}
%>
Subscribe to:
Posts (Atom)