Lukasz Bajzel

Greenhorn
+ Follow
since Dec 03, 2007
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
(keep public parts private until JForum day)
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt
Moderation Tools

Recent posts by Lukasz Bajzel

Inheritance is the capacity by which a class can use the properties and methods of another class while adding its own functionality. In other words it is the ability of a subclass to derive state and behavior from its superclass.

Inheritance gives the opportunity to add some functionality that does not exist in the original class. So the child class has the option of using the behavior as defined in the super class or modify the behavior/add new behavior. Inheritance provides a formal mechanism for code reuse.

The keyword used in inheritance is 'extends'. When a class B 'extends' another class A, we all the class 'B' a child or sub class of 'A'.

class A{
}

class B extends A{
}

Java doesn't support multiple inheritance. That means a class can 'extend' only one class. Each class is allowed to have just one direct superclass, and each superclass has the potential for an unlimited number of subclasses
--------------------

Polymorphism is a capability that helps to assign a different behavior or value in a subclass, to something that was declared in a parent class.

For example, a method can be declared in a parent class, but each subclass can have a different implementation of that method (name remains the same but the implementation differs). This allows each subclass to differ, without the parent class being explicitly aware that a difference exists. Polymorphism allows improved code organization and readability as well as the creation of extensible programs.

Let us take a simple example to illustrate how this works.

class Person{
public String getName(){
return "Person";
}
}

class JavaUser extends Person{
public String getName(){
return "JavaUser";
}
}

Now lets assume that we create two objects like
Person person = new Person();
Person javaUser = new JavaUser();

Although both the objects are of types 'Person' (Look at the left side of = sign),
a call
person.getName() returns -> "Person"
javaUser.getName() returns -> "JavaUser"
because the getName() has a different implementation in the sub class.

Polymorphism in Java is classified into two general types:
----------------------------------------------------------
1. compile-time polymorphism (method overloading type)

Overloading occurs when several methods have same names with different method signature. Overloading is determined at the compile time.Overloaded methods may all be defined in the same class, or may be defined in different classes as long as those classes have a superclass-subclass relationship.

Class Person{
String name;
String preferredName;

setName(String name){
}
setName(String name, String preferred){
}
}


2. run-time polymorphism (method overriding type)

When overriding methods, java 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


An example of runtime polymorphism is below.

class Person{
public String getName(){
return "Person";
}
}

class JavaUser extends Person{
public String getName(){
return "JavaUser";
}
}


Hope you are clear on the concepts now!

Sincerely,
Your friends at www.javaadvice.com
www.javaadvice.com - Your partner in mastering Java.
-------------------
[ January 29, 2008: Message edited by: Lukasz Bajzel ]
10 years ago
In the code posted above , the Outer class is complete (}) before the Innner class is declared. So there is no way you will get access to the class by calling
Outer.Inner inner = outer.new Inner();

Now, if you delete that } and add one at the bottom, the structure becomes ok but then again there are other problems.

1. useInner() method cannot access the object 'inner' because it is local to the main method (as pointed out by the previous post)
2. useOuterInstance variable() is not a valid method. It has to be either useOuterInstance_variable() or useOuterInstancevariable()

Make these changes and go from there.

Btw, the note below will help you refresh what you might already know
----------
A nested class is another member of the outer class so it has access to all the members of the enclosing class irrespective of the access modifiers (private, protect or public).

* Being a member of the outer class, a nested class can be declared private, public or default.
* Again a nested class can be declared static (called static nested class) or non-static ( called inner class)

A static nested class, like any other static member, is an class level structure for the outer class.

public class Outer{
public static class Inner{
}
}

The static nested class 'Inner' is accessed like "Outer.Inner "
To create an object of inner,
Outer.Inner inner = new Outer.Inner();

Now, with a non-static nested class (inner class), the object creation is little tricky. In this case, we need to create an object of the outer class first and then use the outer object to create an object of the inner class

public class Outer{
public class Inner{
}
}

The syntax would be like
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
--------------

Good luck!

Sincerely,
Your friends at www.javaadvice.com
www.javaadvice.com - The one stop resource for all your Java questions and answers
10 years ago
Let us explain what is happening here.

When you call new Sub(), the parent class's (Super) constructor gets invoked. why because, there is no constructor for Sub. So the call propagates in the chain and goes to parents constructor.

Now, when you call abc() in the super class's constructor, the abc() method in Sub is called. Why because remember you invoked new Sub(). But when that call gets executed from the Super's constructor, the variable s1 is not visible.

The result is s1 0

Hope this helps!

Sincerely,
your friends at JavaAdvice.com
http://www.JavaAdvice.com - The one stop resource for all your Java questions and answers
[ January 23, 2008: Message edited by: Lukasz Bajzel ]
10 years ago
Creating a database connection using JDBC involves 3 main steps.
1. Loading the database driver
2. Getting the connection using the driver manager
3. Using the connection to access the underlying database.

The sample code below explains the steps in detail.

import java.sql.*;

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try{
//Load the database driver class
Class.forName("your databse driver name");
//Example, mySql driver is com.mysql.jdbc.Driver

//Get the connection
conn = DriverManager.getConnection( "dburl","user","password") ;

//Create a Statement object.
stmt = conn.createStatement();

//Get a ResultSet

rs = stmt.executeQuery("your query here");

//Loop through the results
while(rs.next()){
//get to each column in a row.
//for example to get a value from a column named 'user'
String userName = rs.getString("user");
}
}catch( Throwable t){
//handle error here
}
finally{

//note the sequence of closing the objects. rs first followed
// by stmt and connection objects
try{
if(rs != null) rs.close();
}catch(Throwable t){t.printStackTrace();}

try{
if(stmt != null) stmt.close();
}catch(Throwable t){t.printStackTrace();}

try{
if(con != null) con.close();
}catch(Throwable t){t.printStackTrace();}
}


Hope this helps!

Sincerly,
Your friends at www.javaadvice.com
www.javaadvice.com - The one stop resource for all your Java questions and answers.
request.setAttribute() sets the value in the current request. When you use RequestDispatcher and forward(), the same request is forwarded to the jsp and you get access to the value set in the attribute.

Now when you click the link, the request gets redirected to the page. So it is another request at this time and the original request and any values associated with it are gone at this point. Clickiing the link never goes to the Servlet again, it is directly redirected to the page by the web server.


Hope this helps!

Sincerly,
Your friends at www.javaadvice.com
www.javaadvice.com - The one stop resource for all your Java questions and answers.
10 years ago
Yes. Both of them calls the constructor with 4 arguments because you have a call like "this(x,y,z,q);". But note that once that call is executed, the control gets back to the original contructor and continue executing the statements there.

We think you got the concept here. Keep exploring..

Sincerly,
Your friends at www.javaadvice.com
www.javaadvice.com - The one stop resource for all your Java questions and answers.
10 years ago
Below is the code to send mail using Java. Make sure that you know the host/smtp-host name and other parameters.


boolean mailSent = false;
try{

Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.host", <your_host> ;
props.put("mail.smtp.host", <your_smtp_host> ;
Session sess = Session.getDefaultInstance(props);
Message msg = new MimeMessage(sess);

String toAddr =<comma seperated address>;

msg.setRecipients( Message.RecipientType.TO, InternetAddress.parse(toAddr));
String rplAddr = mailProps.getProperty("reply_address");
String fromPerson = mailProps.getProperty("from_personal");

InternetAddress fromAddr = new InternetAddress(<your_reply_address> ;

msg.setFrom(fromAddr);
msg.setSubject(<subject> ;
Multipart mp = new MimeMultipart();

BodyPart pixPart = new MimeBodyPart();
pixPart.setContent(content, "text/html"); //for sending text/html mail
msg.setContent(mp);
Transport.send(msg);
mailSent = true;
}catch(Throwable t){
mailSent = false;
//handle exception
}
return mailSent;



Hope this helps!

Sincerly,
Your friends at www.javaadvice.com
www.javaadvice.com - The place where your questions are answered directly.
10 years ago
we are in complete agreement with the replies. We just meant to say that while renameTo() is the default option available, make sure to verify that it succeeds.

The below code can be a platform independent option to perform a copy operation.

import java.io.*;

boolean fileCopied = false;
InputStream in = null;
OutputStream out = null;
String sepr = System.getProperty("file.separator");
try {
in = new FileInputStream(path+sepr+srcFileName);
File newFile = new File(path+sepr+targetFileName);
out = new FileOutputStream(path+sepr+targetFileName);
byte[] buffer = new byte[2048];
while (true) {
synchronized (buffer) {
int length = in.read(buffer);
if (length != -1) {
out.write(buffer, 0, length);
}
else
break;
}
}

File oldFile = new File(path+sepr+srcFileName);
fileCopied = newFile.exists();
}
catch(Throwable t){
//handle exceptions here.
}
finally {
try{
if (in != null) { in.close();}
if (out != null) { out.close(); }
}catch(Throwable t1){}
}
return fileCopied;

Still, note that this is the code to do a copy operation. (It doen't move any file)


Hope this is more clear now.

Sincerly,
Your friends at www.javaadvice.com
www.javaadvice.com - The place where your questions are answered directly.
10 years ago
You defined 3 constructors here.
1. No parms
2. 2 parms
3. 3 Parms

So when you create an instance of the class by calling new Rectangle(), the constructor with no parm (1) gets invoked. When you use new Rectangle(20,20) the second contructor only gets called. No other constructors are invoked. Similarly with the 3 parm option, the third one will get called.

Now since you have this(0, 0, 0, 0); code in the costructor 1, a call new Rectangle() will eventually cause the cotrol to go to constructor 3. Similar is the case with constructor 2 . But note that only the new Rectangle() call goes to constructor 1. When you use new Rectangle(20,20), it control goes to constructor 2 but will never go to constructor 1.


Hope this helps!

Sincerly,
Your friends at www.javaadvice.com
www.javaadvice.com - The place where your questions are answered directly.
10 years ago
A best place to start would be the Java Tutorial from Sun. Go to java.sun.com and look for the Tutorial.

Sincerly,
Your friends at www.javaadvice.com
www.javaadvice.com - The place where your questions are answered directly.
10 years ago
As mentioned by other ranchers, renameTo() is a tricky option.

Per the API documentation "Many aspects of the behavior of this method (renameTo() )are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful."

So it is the responsibility of the programmer to make sure that the rename really works. we would recommend to write your own code to move the file rather than relying on renameTo() method.

Sincerly,
Your friends at www.javaadvice.com
www.javaadvice.com - The place where your questions are answered directly.
10 years ago
The access modifiers in Java are 'public, private, protected, or package-private (no modifier)'

In Java there are two levels of access control.

1. The class level or top level (public or package-private access)
2. The memeber level (public, private, protected, or package-private)

The class level:

When a class is declared 'public', it is visible across packages. But when it is defined package-private or default (that is without any modifier), the class is visible only to other classes within the same package.

public class JavaAdvice -> visible across packages.
class JavaAdvice -> visible only within the package.

At the class level only public or default access are allowed

--

The memeber level:

The following table shows the access to members permitted by each modifier.

Access Levels:

Modifier Class Package Subclass World
-------- ----- ------- ------- ------
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N


In Summary,
A class can be defined public or default (no modifier) and class members are allowed to have one of 'public, private, protected, or package-private (no modifier)'. Public members are visible across packages. Any private member of a class is not visible outside of the class. Any protected members are available to the class and its subclass. Default members are visible in the class and within the same package.



Hope this helps!

Sincerly,
Your friends at www.javaadvice.com
www.javaadvice.com - The place where your questions are answered directly.
10 years ago
Here is an example of reading lines from a file

import java.io.*;

BufferedReader fileHandle = null;
try{
//Use buffering to speed up the process
fileHandle = new BufferedReader(new FileReader("file_path"));
/*
* Note: Make sure to use System.getProperty("file.separator")
* to seperate directories in any path being passed.
*/
String line;
//When file is available and ready to read.
if(fileHandle != null && fileHandle.ready() ){

//read one line at a time.
while((line = fileHandle.readLine()) != null){
//work with the line
System.out.println(line);
}
}
}catch(Throwable t){
t.printStackTrace();
}
finally{
try{
if (fileHandle != null) {
fileHandle.close();//close the reader.
}
}catch (IOException ie) {
ie.printStackTrace();
}

}


Hope this helps!

Sincerly,
Your friends at www.javaadvice.com
www.javaadvice.com - The place where your questions are answered directly.
10 years ago
We would suggest you to look at an open source API - JDOM. JDOM is an XML parsing API exclusively for Java. It uses DOM API to parse XML files and make the parsed data availabe as Java objects. It can be downloaded from jdom.org. Most the questions are answered in their tutorial, but if you need any help, let us know.


Hope this helps!

Sincerly,
Your friends at www.javaadvice.com
www.javaadvice.com - The place where your Java questions are answered directly.
10 years ago
You can schedule jobs in Java using the java.util.Timer and java.util.TimerTask classes.

Lets say you have a TimerTask class

private class MyTimerTask extends TimerTask{
.....
public void run(){...}
}

then you can use code similar to
new Timer().scheduleAtFixedRate(new MyTimerTask(), delay_in_starting,1000*24*60*60);

Where delay_in_starting is the the time in milliseconds before the task starts and 1000*24*60*60 represents 24 hours (means the task will run once in every 24 hours)

The above code is just to show how to use these classes to achieve what you want. You may elaborate on that..

Hope this helps!

Sincerly,
Your friends at www.javaadvice.com
www.javaadvice.com - The one stop resource for all your Java questions and answers.
10 years ago