what is method overriding in java ?

Hi All,
In this post we will discuss about the method over riding in java

Description:-
Method overriding is the process of defining the same method with same signature in child class.

Purpose:-
Method overriding is helpful for defining their own functionalities of child class with same name as parent class method. which will improve the readability.

Example:-

class Company{
int getSalary(){
// will return default salary for every comapany
}
}

class ABC extends Company{
int getSalary(){
// will return ABC company salary
}
}

class XYZ extends Company{
int getSalary(){
// will return XYZ comapany salary
}
}

Points to Note:-

1. Overridden methods of ABC and XYZ will return their respective salaries.
2. Method signatures of both parent and child class should be same.
3. Access modifiers of child class overridden method should be less restrive than parent methods.
for exmaple if the parent class overridden method has the access specifier as protected then child
class overridden method should not be having private as access specifier it will result in compile
compile time error.

Points to remember:-

1. Method overriding cannot be applicable for static, final and private methods because these are related
to class itself.
2. We can write same static method of parent in child class with the same signature but that method will
always refer to scope of that class itself.
3. Method overriding is the concept of runtime method dispatch with means compiler can’t decide calling of
method (child class method or parent class method) in compile time.

Logical questions to interview:-

1. what is the output of the below program.

class Base {
static void display(){
System.out.println(“Base static”);
}

void print(){
System.out.println(“Base instance”);
}
}
class Derived extends Base {
static void display(){
System.out.println(“Derived static”);
}

void print(){
System.out.println(“Derived instance”);
}
}
class Main {
public static void main(String args[]){
Base base = new Derived();
base.display();
base.print();
}
}

Answer:-
1. base.display() – will print “Base static” as output because static will always belongs to class itself.
2. base.print() – will print “Derived instance” as output because it is instance method of that object.

Method overriding and overloading comes under polymorphism of oops concepts. If you have any queries fell free to add comments.

How to change the existing column name,type and auto increment in postgres and mysql?

Hi,

We can rename column by using the following queries

//postgres
In postgres renaming a column is straight forword we can simply give rename to keywords.
alter table tablename rename column existingcolumnname to newcolumnname;

//mysql
In mysql, for renaming a column we need to use change keyword.
alter table tablename change existingcolumname newcolumnname old or new datatype;

We can add primary key to the existing column by using the following queries.

//postgres
In postgres we can add primary key by using following query.

alter table tablename add primary key(columnname);

In postgres there is no auto increment we can call it as serial. we can add serial for existing
columns by using following queries.

i. First we need to create a sequence by using the following query.
create sequence sequencename;

ii. Second we need to set the sequence to the column for which we need serial by using the
following queries.

alter table tablename alter column columnname set default nextval(‘sequencename’);
alter table tablename alter column columnname set not null;

//to change the value of sequence
SELECT MAX(a) FROM tablename;
SELECT setval(‘sequencename’, value got by the above query);
//mysql
In mysql we can add primary key and auto increment by using following queries.
i. we can drop the colum which we need to add the primary key and autoincrement
by using the following query.
alter table tablename drop column columnname;
ii. add primary key and auto increment to the column.
alter table tablename add column columnname datatype primary key auto_increment;

How to change the existing iPhone xibs into iPad xibs ?

Hi

Here we are going to see the steps to convert existing iPhone xibs into iPad xibs.

1. Select the iPhone xib and click on File menu click on duplicate.
2. Rename the xib name with the (tilt symbol) ~ipad at the end.(example1~ipad.xib)
3. Now the xib will be saved below the existing iPhone xib.
4. Add ~iphone text at the end of the file of iphone xib. (example1~iphone.xib)(system automatically take the xibs based on the device)

Note:-
For example if we have iPhone xib as example1.xib
when we follow the above steps.
the two xibs will be example1~ipad.xib and example1~iphone.xib.(system automatically take the xibs based on the device) 

5. Now left click on newly created iPad xib and open as source code in Xcode.
6. Now change the document tag type and target run time to iPad.
see below
<document type=”com.apple.InterfaceBuilder3.CocoaTouch.iPad.XIB” version=”3.0″ toolsVersion=”5056″ systemVersion=”13C64″ targetRuntime=”iOS.CocoaTouch.iPad” propertyAccessControl=”none“>

7. Now Again click on the file open as Interface Builder- iOS.
8. Now go to Attribute inspector simulated matrix -> size -> iPad Full Screen.

Note:- All these changes i done in Xcode 5.1.1.

What are the different types of delegate methods available in UITableView with Description?

Hi,

Here we have a list of all the methods and their descriptions for UITableView(UITableViewDelegate and UITableViewDataSource) Protocols.

UITableViewDelegate Protocol:-

@protocol UITableViewDelegate<NSObject, UIScrollViewDelegate>

@optional

customization 

– (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath;

Description:-

TableView sends this message to its delegate just before it uses cell to draw a row and to customize the cell object before it displayed. This method is often used for overriding state based properties set earlier by the table view like selection and background color.

Height support

– (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

Description:-

This method allows us to specify rows with varying heights. (Returned Height should be less than are equal to 2009) If we implement this method this overrides the rowHeight property of the tableview.

– (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;

Description:-

This method allows us to specify section headers with varying heights (From iOS 5.0 and later we must return the actual height for each section header).

– (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;

Description:-

This method allows us to specify section footers with varying heights (works only in table view style grouped).

Header and Footer Sections

– (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;

Description:-
This method allows us to customize the header view of a section it returns an object that can be UILabel or UIImageView or a customView this method only works correctly when we implement heightForHeaderInSection method also. And this will be adjusted to default or specified header height.

(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;

Description:-

This method allows us to customize the footer view of a section it returns an object that can be UILabel or UIImageView or a customView this method only works correctly when we implement heightForFooterInSection method also. And this will be adjusted to default or specified footer height.

Accessories (disclosures).

– (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath

Description:- (Deprecated in iOS 3.0).

– (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath;

Description:-

This method responds when we tap on disclosure button. It won’t respond, If it is called when an accessory view is set for the row at indexPath.

// Selection

These methods are called before the user changes the selection and return a new indexPath, or nil, to change the proposed selection.

– (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath;

Description:-
This method called when the user tap and release the touch even though the row is highlighted when the user touches it won’t get called it called when the user releases the touch on row. And it won’t be called when the table is in editing mode.

– (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath;

Description:-
This method is only called if there is an existing selection when the user tries to select a different row. The delegate is sent this method for the previously selected row.

These methods are called after the user changes the selection.
– (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

Description:-
This method we will use mostly and is called when we select a cell and it can be use to set disclosure images when we select a row.This method is not called when the editing property of the table is set to yes.

– (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath;

Description:-
Row deselections handled in this method for example we can remove the disclosure images associated with the row.

For Editing

Those methods allows customization of the editingStyle for a particular cell located at indexPath.
If not implemented, all editable cells will have UITableViewCellEditingStyleDelete set for them when the table has editing property set to YES.

– (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath;

Description:-
This methods allows us to customize the editing style of a cell located at indexPath.

– (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath;

Description:-
We can delete a row either by swapping or tapping the red minus icon in editing mode that time Delete button has a title like “Delete”.
we can implement this method to return an alternative title.

– (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath;

Description:-
This method controls whether the background is indented while editing.
If this method is not implemented, the default value is YES. This is unrelated to the indentation level below. This method only applies to grouped style table views.

– (void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath;
– (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath;

Description:-

The willBegin/didEnd methods are called whenever the ‘editing’ property is automatically changed by the table (allowing insert/delete/move).
This is done by a swipe activating a single row. In €œswipe to delete mode the table view does not display any insertion, deletion, and reordering controls. These methods give the delegate an opportunity to adjust the application’€™s user interface to editing mode.

Moving or Reordering
– (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath;

Description:-
This method allows customization of the target row for a particular row as it is being moved/reordered. As the dragged row hovers over another row, the destination row slides downward to visually make room for the relocation (This is the location identified by proposedDestinationIndexPath).

Indentation
– (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath;
Description:-
This method returns depth of row for hierarchies.

@end

UITableViewDataSource Protocol:-

This protocol contains some required methods to implement when we implement this protocol.
This protocol represents the data model object and such as it supplies no information about appearance it only deals with the data.Data source provides the table-view object with the information it needs to construct and modify a table view.

@protocol UITableViewDataSource<NSObject>

@required

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
Description:-
This is the required method to implement and it returns the number of rows in a particular section.

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
Description:-
This is row display. Implementers should always try to reuse cells by setting each cell’s reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier.
Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls).It returns a cell which is reusable and this is the place where we can customize our cell data and this is the important method of all.

@optional
– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;

Description:-
This method reruns the number of sections in a tableview if you don’t implement this method the default number of sections are one.

– (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
– (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;
Description:-
It returns string to use as the title of the section header if it is nil header will be displayed with the empty title. We can use custom view for different font styles.

 Editing
– (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;
Description:-
This method allows us to individual rows can opt out of having the -editing property set for them. If not implemented, all rows are assumed to be editable.

Moving or Reordering

– (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath;

Description:-
This method allows the reorder accessory view to optionally be shown for a particular row. By default, the reorder control will be shown only if the datasource implements -tableView:moveRowAtIndexPath:toIndexPath:. If it returns YES that means row can be moved other wise row cannot be moved.

 Index
– (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;

Description:-
This method returns an array of section titles to display in section index view (e.g. “A” through “Z” ( “ABCD…Z#”)) and the table view must be in the plain style.

– (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index;

Description:-
This method tell table which section corresponds to section title/index (e.g. “B”,1).There are two index numbers those are an index to an section index title in the array returned by sectionIndexTitlesForTableView:, and an index to a section of the table view; the former is passed in, and the latter is returned.

Data manipulation – insert and delete support
– (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;
Description:-
After a row has the minus or plus button invoked (based on the UITableViewCellEditingStyle for the cell), the dataSource must commit the change.

Data manipulation – reorder / moving support
– (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath;
This method is used for reordering of the rows.

@end

When I Write this Blog I took the help of below links.

Thank You.

Source:-

https://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UITableViewDelegate/tableView:willDisplayCell:forRowAtIndexPath:

https://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewDataSource_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UITableViewDataSource/tableView:moveRowAtIndexPath:toIndexPath:

http://stackoverflow.com/questions/5831813/delegate-and-datasource-methods-for-uitableview

How do we add bottom line to the last cell in UITableView in iOS?

Hi,

In iOS 7 there is no bottom line for the last cell in tableview we need to add separator view for the last cell.

Add below code to the cellForRowAtIndexPath before returning the cell

      if([rowOfTheTable count] –1 == indexPath.row){    // replace the rowsOfTheTable with the array                                                                                    //you are providing to the table view.

UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height – 2 , self.view.frame.width, 0.5)];

    separatorLineView.backgroundColor = [UIColor lightGrayColor];      

        [cell addSubview:separatorLineView];

   }

It will work and add a separator line to the end of the cell of your table view.

What are singleTon objects and How do we create in Java also in cocos2dx ?

1. Singleton objects are mainly used for handling global data.

2. Singleton purpose is to control object creation and limiting to create number of objects to one.

In cocos2dx we see some of the singleton objects like 

      CCDirector::sharedDirector()->delegate.(delegate eg: winSize,convertoGL etc).

in objective c we see some of the singleton objects like

      [UIApplication sharedApplication].delegate

How do we crate singleton objects in Objective C

//interface somefiel.h

   @interface MyManager : NSObject

    + (id) sharedManager;  // this is a class method thats why we preceded with + sign and returns id 

   @end

 // interface implementation  somefile.m

  @implementation MyManager

    + (id) sharedManager {

        static id sharedManager = nil;  //here sharedManger is a static variable we know that static variables are initilised only once                //when the program is loaded so need not worry about shareManager is null everytime the method is called.

    //  static local variable is remains in memory for the life of the program and it is accessable only to one method. 

      if(sharedManager == nil){

         sharedManager = [[self alloc] init];

        }

        return sharedManger;

     }

  @end

// when the first time shareManger is called the object is null so it creates an object and returns it we when it is called second time it returns the object which is created previously.

In Java:

 we can create singleton objects in java by the following code 

 I Method

  public class SingletonObject {

   private static SingletonObject singleton = new SingletonObject(); // this should be static

   private SingletonObject(){    // constructor should be private in order to restric the creation of object 

    }

    public static SingletonObject getInstance(){

     return singleton;

    }

   }

II Method

  public class SingletonObject {

 private static SingletonObject singleton = null;

 private SingletonObject(){}

public static SingletonObject getInstance(){

   if(singleton == null ){

   singleton = new SingletonObject();

    } 

return singleton;

}

 }

How do we create a login page centered in html?

<html>

<head><title>My Login Page</title>

<style type=”text/css”>

#loginPage{

margin:20% auto;
width:200px;

}

</style>

</head>

<body>

<form action=”index.jsp” method=”post” id=”loginPage”>

<input type="text" name="userName" placeholder="Enter Username" autocapitalize="off"/><br />
<input type="password" name="passWord" placeholder="Enter Password"/><br />
<input type="checkbox" name="remember">RememberMe<br />
<input type="submit" value="Log In" name="login"/>

 </form>

</body>

</html>

How do we create bodies in box2d with cocos2dx?

Hi

Before going to work with box2d we need to know something about box2d like what it is and how it works.

What is box2d?

Box2D is a 2D rigid body simulation library for games. We can use it in our games to make objects move in believable ways and make the game world more interactive. From the game engine’s point of view a physics engine is just a system for procedural animation.

Box2D is written in portable C++. All of the keywords in box2d stars with b2 prefix.This is sufficient to avoid name clashing with your game engine.

Here we should know some c++ programming skills like compiling, linking, and debugging before working with Box2D.

Steps to follow to create bodies in box2d:-

1. Paste the box2d library into your project directory.

2. Include(export) the Box2D.h file into your main layer class.

3. create instance variable in your interface file or .h file.

For example here I am creating a Ball Body.
// GameLayer.h
b2World *_world;
b2Body *_ballBody;
4. Implement the GameLayer.cpp file like below
// In your inti method
1. At first create b2World
// A physics world is a collection of bodies, fixtures, and constraints that interact together.
// Box2D supports the creation of multiple worlds, but this is usually not necessary or desirable.
// This is the main container for all the bodies to simulate in your game.

// create world
b2Vec2 gravity = b2Vec2(0.0f, -9.8f); // is a vector for pulling the objects downwords like gravity pulls objects in real world
b2World = new b2World(gravity);
2. create ball body
// in order to create a body we need to follow the following steps
i) create body definition
/// A body definition holds all the data needed to construct a rigid body.
/// You can safely re-use body definitions. Shapes are added to a body after construction.

// create ball costume
CCSprite *_ball = CCSprite::create(“ball.png”); // is used for userdata which is used for simulation
_ball->setPosition(ccp(100,100));
_ball->setTag(1);
addChild(_ball);

b2BodyDef ballBodyDef; // ball definition
ballBodyDef.type = b2_dynamicBody; // we have three types of bodies 1.dynamic 2.static 3.kinematic
/* b2_staticBody
A static body has does not move under simulation and behaves as if it has infinite mass.
Internally, Box2D stores zero for the mass and the inverse mass. Static bodies can be moved manually by the user.
A static body has zero velocity. Static bodies do not collide with other static or kinematic bodies.

b2_kinematicBody
A kinematic body moves under simulation according to its velocity. Kinematic bodies do not respond to forces.
They can be moved manually by the user, but normally a kinematic body is moved by setting its velocity.
A kinematic body behaves as if it has infinite mass, however, Box2D stores zero for the mass and the inverse mass.
Kinematic bodies do not collide with other static or kinematic bodies.

b2_dynamicBody
A dynamic body is fully simulated. They can be moved manually by the user, but normally they move according to forces.
A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass.
If you try to set the mass of a dynamic body to zero, it will automatically acquire a mass of one kilogram.*/

ballBodyDef.position.Set(100/PTM_RATIO, 100/PTM_RATIO); // PTM_RATIO 32(Box2d uses meteres instead of pixels so we need to use this).
ballBodyDef.userData = _ball; // assign ball image
b2Body * ballBody = _world->CreateBody(&ballBodyDef); // create body

ii) create shape
// Shapes describe collision geometry and may be used independently of physics simulation.
// You may perform several operations with shapes.
b2CircleShape circle;
circle.m_radius = half radius of the ball/PTM_RATIO;

iii) create a fixture for the body
/// A fixture definition is used to create a fixture. This class defines an
/// abstract fixture definition. You can reuse fixture definitions safely.
/* Box2D provides the b2Fixture class to attach shapes to bodies. Fixtures hold the following:

a single shape
broad-phase proxies
density, friction, and restitution
collision filtering flags
back pointer to the parent body
user data
sensor flag */

b2FixtureDef ballShapeDef; //ball shape definiton
ballShapeDef.shape = &circle; // give shape of circle which we have created earlier
ballShapeDef.density = 1.0f; // give density of ball which will affect the gravity. Density values ranging form 0.0 to 1.0.
ballShapeDef.friction = 0.0f; // friction ranging from 0 to 1.
ballShapeDef.restitution = 1.0f; // the bounching capacity ot the ball ranging from 0.0 to 1.

_ballFixture = ballBody->CreateFixture(&ballShapeDef);

3.Simulate the world

_world->Step(dt,10,10);
for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) {
if (b->GetUserData() != NULL) {
CCSprite *sprite = (CCSprite *)b->GetUserData();
sprite->setPosition(ccp(b->GetPosition().x * PTM_RATIO,
b->GetPosition().y * PTM_RATIO));
sprite->setRotation(-1 * CC_RADIANS_TO_DEGREES(b->GetAngle()));
}
}
5. Now delete the world in destructor for memory management
delete _world;

 

How to create an EJB with Web Sphere in Ubuntu ?

In order to create an ejb porject we need ejb.jar file and dynamicproject.war file and our actual .ear file to deploy into the websphere.

1. Create ejb project i.e (ejb-jar.xml)

  eg: ejb-jar.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<ejb-jar id=”ejb-jar_ID” version=”2.1″
xmlns=”http://java.sun.com/xml/ns/j2ee&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd”&gt;
<display-name>This is the display name</display-name>
<enterprise-beans>
<session>
<ejb-name>give your ejb name</ejb-name>
<home>com.example.some.model.MarketHome</home>
<remote>com.example.some.model.Market</remote>
<local-home>com.example.some.model.MarketLocalHome</local-home>
<local>com.example.some.model.MarketLocal</local>
<ejb-class>com.example.tadawul.model.MarketBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Bean</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>

2. Create Dynamic web project and add ejb project as dependency project.(Note: all these are done in eclipse)

3. Create Enterprise Application project that contains

      Application.xml file which includes ejb.jar file and dynamicproject.war file(also includes web.xml file).

Exprort into websphere:-

1. Go to your websphere home directory 

         eg: ../IBM/Web Sphere/AppServer/bin

2. Start server: 

        eg:- ./startserver.sh server1

3. logs will be available in 

        eg: ../IBM/WebSphere/Appserver/profiles/Appserver1/logs/server1

4. Launch the server in browser

    https:/localhost:9043/ibm/console/login.d?action=secure

5. Run your project 

      http://localhost:9080/projecthome 

6. Deploy the ear into websphere.

7. And give the JNDI name for the project which will be used in the lookup(” “) context.

8. Give context-root in the address of the browser which can be found in the application.xml file in enterprise application project.

To work with database in webSphere

1. Add mysql connector to ejb project and also add mysql connector to deployment assymbly of ear project.

2. Go to properties -> Deployment Assembly -> Add -> archieves from file system.

3. Also place mysql connector into the IBM/Web Sphere/AppServer/lib folder.