Thursday, February 18, 2010

Inner Classes in Java Example Program

Java Inner Class Example Codes

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

/**
* This program demonstrates the use of inner classes.
*/

public class InnerClassTest
{
public static void main(String[] args)
{
TalkingClock clock = new TalkingClock(1000, true);
clock.start();

// keep program running until user selects "Ok"
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}

/**
* A clock that prints the time in regular intervals.
*/
class TalkingClock
{
/**
* Constructs a talking clock
* @param interval the interval between messages (in milliseconds)
* @param beep true if the clock should beep
*/
public TalkingClock(int interval, boolean beep)
{
this.interval = interval;
this.beep = beep;
}

/**
* Starts the clock.
*/
public void start()
{
ActionListener listener = new TimePrinter();
Timer t = new Timer(interval, listener);
t.start();
}

private int interval;
private boolean beep;

public class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println("At the tone, the time is " + now);
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
}


<< Back == Next >>

Read more...

Sample Java Codes for Interface

Comparable interface Java Example Codes

import java.util.*;

/**
* This program demonstrates the use of the Comparable interface.
*/

public class EmployeeSortTest
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];

staff[0] = new Employee("Harry Hacker", 35000);
staff[1] = new Employee("Carl Cracker", 75000);
staff[2] = new Employee("Tony Tester", 38000);

Arrays.sort(staff);

// print out information about all Employee objects
for (Employee e : staff)
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
}
}

class Employee implements Comparable
{
public Employee(String n, double s)
{
name = n;
salary = s;
}

public String getName()
{
return name;
}

public double getSalary()
{
return salary;
}

public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}

/**
* Compares employees by salary
* @param other another Employee object
* @return a negative value if this employee has a lower salary than
* otherObject, 0 if the salaries are the same, a positive value otherwise
*/
public int compareTo(Employee other)
{
if (salary <>
if (salary > other.salary) return 1;
return 0;
}

private String name;
private double salary;
}


<< Back == Next >>

Read more...

Java Clone sample Codes

Cloning in Java

import java.util.*;

/**
* This program demonstrates cloning.
*/

public class CloneTest
{
public static void main(String[] args)
{
try
{
Employee original = new Employee("John Q. Public", 50000);
original.setHireDay(2000, 1, 1);
Employee copy = original.clone();
copy.raiseSalary(10);
copy.setHireDay(2002, 12, 31);
System.out.println("original=" + original);
System.out.println("copy=" + copy);
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}

class Employee implements Cloneable
{
public Employee(String n, double s)
{
name = n;
salary = s;
hireDay = new Date();
}

public Employee clone() throws CloneNotSupportedException
{
// call Object.clone()
Employee cloned = (Employee) super.clone();

// clone mutable fields
cloned.hireDay = (Date) hireDay.clone();

return cloned;
}

/**
* Set the hire day to a given date.
* @param year the year of the hire day
* @param month the month of the hire day
* @param day the day of the hire day
*/
public void setHireDay(int year, int month, int day)
{
Date newHireDay = new GregorianCalendar(year, month - 1, day).getTime();
// Example of instance field mutation
hireDay.setTime(newHireDay.getTime());
}

public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}

public String toString()
{
return "Employee[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]";
}

private String name;
private double salary;
private Date hireDay;
}


<< Back == Next >>

Read more...

Anonymous Inner Classes Program in Java

Anonymous Inner Classes

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

/**
* This program demonstrates anonymous inner classes.
*/

public class AnonymousInnerClassTest
{
public static void main(String[] args)
{
TalkingClock clock = new TalkingClock();
clock.start(1000, true);

// keep program running until user selects "Ok"
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}

/**
* A clock that prints the time in regular intervals.
*/
class TalkingClock
{
/**
* Starts the clock.
* @param interval the interval between messages (in milliseconds)
* @param beep true if the clock should beep
*/
public void start(int interval, final boolean beep)
{
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println("At the tone, the time is " + now);
if (beep) Toolkit.getDefaultToolkit().beep();
}
};
Timer t = new Timer(interval, listener);
t.start();
}
}


<< Back == Next >>

Read more...

Java Classes Features by Reflection

Features of Java Classes

import java.util.*;
import java.lang.reflect.*;

/**
* This program uses reflection to print all features of a class.
*/

public class ReflectionTest
{
public static void main(String[] args)
{
// read class name from command line args or user input
String name;
if (args.length > 0) name = args[0];
else
{
Scanner in = new Scanner(System.in);
System.out.println("Enter class name (e.g. java.util.Date): ");
name = in.next();
}

try
{
// print class name and superclass name (if != Object)
Class cl = Class.forName(name);
Class supercl = cl.getSuperclass();
String modifiers = Modifier.toString(cl.getModifiers());
if (modifiers.length() > 0) System.out.print(modifiers + " ");
System.out.print("class " + name);
if (supercl != null && supercl != Object.class) System.out.print(" extends "
+ supercl.getName());

System.out.print("\n{\n");
printConstructors(cl);
System.out.println();
printMethods(cl);
System.out.println();
printFields(cl);
System.out.println("}");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
System.exit(0);
}

/**
* Prints all constructors of a class
* @param cl a class
*/
public static void printConstructors(Class cl)
{
Constructor[] constructors = cl.getDeclaredConstructors();

for (Constructor c : constructors)
{
String name = c.getName();
System.out.print(" ");
String modifiers = Modifier.toString(c.getModifiers());
if (modifiers.length() > 0) System.out.print(modifiers + " ");
System.out.print(name + "(");

// print parameter types
Class[] paramTypes = c.getParameterTypes();
for (int j = 0; j <>
{
if (j > 0) System.out.print(", ");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}

/**
* Prints all methods of a class
* @param cl a class
*/
public static void printMethods(Class cl)
{
Method[] methods = cl.getDeclaredMethods();

for (Method m : methods)
{
Class retType = m.getReturnType();
String name = m.getName();

System.out.print(" ");
// print modifiers, return type and method name
String modifiers = Modifier.toString(m.getModifiers());
if (modifiers.length() > 0) System.out.print(modifiers + " ");
System.out.print(retType.getName() + " " + name + "(");

// print parameter types
Class[] paramTypes = m.getParameterTypes();
for (int j = 0; j <>
{
if (j > 0) System.out.print(", ");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}

/**
* Prints all fields of a class
* @param cl a class
*/
public static void printFields(Class cl)
{
Field[] fields = cl.getDeclaredFields();

for (Field f : fields)
{
Class type = f.getType();
String name = f.getName();
System.out.print(" ");
String modifiers = Modifier.toString(f.getModifiers());
if (modifiers.length() > 0) System.out.print(modifiers + " ");
System.out.println(type.getName() + " " + name + ";");
}
}
}


<< Back == Next >>

Read more...

Example Programs for Java Abstract Classes

Abstract Classes in Java

import java.util.*;

/**
* This program demonstrates abstract classes.
*/

public class PersonTest
{
public static void main(String[] args)
{
Person[] people = new Person[2];

// fill the people array with Student and Employee objects
people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
people[1] = new Student("Maria Morris", "computer science");

// print out names and descriptions of all Person objects
for (Person p : people)
System.out.println(p.getName() + ", " + p.getDescription());
}
}

abstract class Person
{
public Person(String n)
{
name = n;
}

public abstract String getDescription();

public String getName()
{
return name;
}

private String name;
}

class Employee extends Person
{
public Employee(String n, double s, int year, int month, int day)
{
super(n);
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}

public double getSalary()
{
return salary;
}

public Date getHireDay()
{
return hireDay;
}

public String getDescription()
{
return String.format("an employee with a salary of $%.2f", salary);
}

public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}

private double salary;
private Date hireDay;
}

class Student extends Person
{
/**
* @param n the student's name
* @param m the student's major
*/
public Student(String n, String m)
{
// pass n to superclass constructor
super(n);
major = m;
}

public String getDescription()
{
return "a student majoring in " + major;
}

private String major;
}


Read more...

Java Source code for Reflection to Spy on Objects

Reflection to Spy on Objects

import java.lang.reflect.*;
import java.util.*;

/**
* This program uses reflection to spy on objects.
*/
public class ObjectAnalyzerTest
{
public static void main(String[] args)
{
ArrayList squares = new ArrayList();
for (int i = 1; i <= 5; i++)
squares.add(i * i);
System.out.println(new ObjectAnalyzer().toString(squares));
}
}

class ObjectAnalyzer
{
/**
* Converts an object to a string representation that lists all fields.
* @param obj an object
* @return a string with the object's class name and all field names and
* values
*/
public String toString(Object obj)
{
if (obj == null) return "null";
if (visited.contains(obj)) return "...";
visited.add(obj);
Class cl = obj.getClass();
if (cl == String.class) return (String) obj;
if (cl.isArray())
{
String r = cl.getComponentType() + "[]{";
for (int i = 0; i <>
{
if (i > 0) r += ",";
Object val = Array.get(obj, i);
if (cl.getComponentType().isPrimitive()) r += val;
else r += toString(val);
}
return r + "}";
}

String r = cl.getName();
// inspect the fields of this class and all superclasses
do
{
r += "[";
Field[] fields = cl.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
// get the names and values of all fields
for (Field f : fields)
{
if (!Modifier.isStatic(f.getModifiers()))
{
if (!r.endsWith("[")) r += ",";
r += f.getName() + "=";
try
{
Class t = f.getType();
Object val = f.get(obj);
if (t.isPrimitive()) r += val;
else r += toString(val);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
r += "]";
cl = cl.getSuperclass();
}
while (cl != null);

return r;
}

private ArrayList visited = new ArrayList();
}



Read more...

About This Blog

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP