Problems with abstract classes
I'm reading Java Wireless Blueprints and i'm confused with the functionality of abstract classes, especially in the next section:
public byte[] getPoster() throws ApplicationException {
if (poster == null) {
try {
poster =
ModelObjectLoader.getInstance().getMoviePoster(primaryKey);
} catch (ModelException me) {
throw new ApplicationException();
return poster;
This class invoque to the ModelObjectLoader class that is abstract and after invoque getInstance().getMoviePoster(primaryKey); method. The source code of the class is:
public abstract class ModelObjectLoader {
private static ModelObjectLoader instance = null;
protected ModelObjectLoader() {
instance = this;
return;
public static ModelObjectLoader getInstance() {
return instance;
public abstract TheaterSchedule getTheaterSchedule(Theater theater)
throws ModelException, ApplicationException;
public abstract Movie getMovie(String movieKey)
throws ModelException, ApplicationException;
public abstract Movie getMovie(Movie movie)
throws ModelException, ApplicationException;
public abstract byte[] getMoviePoster(String movieKey)
throws ModelException, ApplicationException;
public abstract int[][] getMovieShowTimes(String theaterKey, String movieKey)
throws ModelException, ApplicationException;
public abstract SeatingPlan getSeatingPlan(String theaterKey,
String movieKey,
int[] showTime) throws ModelException,
ApplicationException;
I don�t find where is the implementation of the getMoviePoster(primaryKey) method.
Can you help me to understand.
Thanks
public abstract byte[] getMoviePoster(String movieKey)It's an abstract method, which means that any concrete class that extends ModelObjectLoader must implement the method. If you really need to know (you might not), then call getInstance() and output the result of getClass().getName() on that object. That will tell you its type, and then you can go look at the source.
Similar Messages
-
Inheritance problem with parent class calling child class
I have a problem with inheritance with a parent class calling a child class method. Below is the example pseudocode code and my problem:
public abstract class A {
protected void function1 ( ) { }
protected void function2 () {
//calls function1();
function1();
public abstract class B extends A {
protected void function1 () {
// do stuff
public class C extends B {
protected void function1 () {
// do stuff
super.function1 ();
}I have an object instance of class C created and its function2() is invoked.
My problem is, while in function2(), which belongs to abstract class A and the method call to function 1() is called, the call invokes the function1() of class B. Shouldn't the call invoke function 1() of class C instead? And then function1() of class B will be called after due to the super.function1(). It's not behaving like I thought it would.
Edited by: crono77 on Jan 10, 2008 8:13 PMNevermind, i found my error :)
-
Getting problem with DOMImplementation classes method getFeature() method
hi
getting problem with DOMImplementation classes method getFeature() method
Error is cannot find symbol getFeature()
code snippet is like...
private void saveXml(Document document, String path) throws IOException {
DOMImplementation implementation = document.getImplementation();
DOMImplementationLS implementationLS = (DOMImplementationLS) (implementation.getFeature("LS", "3.0"));
LSSerializer serializer = implementationLS.createLSSerializer();
LSOutput output = implementationLS.createLSOutput();
FileOutputStream stream = new FileOutputStream(path);
output.setByteStream(stream);
serializer.write(document, output);
stream.close();
problem with getFeature() methodYou are probably using an implementation of DOM which does not implement DOM level-3.
-
Problems with inner classes in JasminXT
I hava problems with inner classes in JasminXT.
I wrote:
;This is outer class
.source Outer.j
.class Outer
.super SomeSuperClass
.method public createrInnerClass()V
.limit stack 10
.limit locals 10
;create a Inner object
new Outer$Inner
dup
invokenonvirtual Outer$Inner/<init>(LOuter;)V
;test function must print a Outer class name
invokevirtual Outer$Inner/testFunction ()V
.end method
;This is inner class
.source Outer$Inner.j
.class Outer$Inner
.super java/lang/Object
.field final this$0 LOuter;
;contructor
.method pubilc <init>(LOuter;)V
.limit stack 10
.limit locals 10
aload_0
invokenonvirtual Object/<init>()V
aload_0
aload_1
putfield Inner$Outer/this$0 LOuter;
return
.end method
;test
.method public testFunction ()V
.limit stack 10
.limit locals 10
;get out object
getstatic java/io/PrintStream/out java/io/PrintStream;
aload_0
invokevirtual java/lang/Object/getClass()java/lang/Class;
;now in stack Outer$Inner class
invokevirtual java/Class/getDeclaringClass()java/lang/Class;
;but now in stack null
invokevirtual java/io/PrintStream/print (Ljava/lang/Object;)V
.end methodI used dejasmin. Code was equal.
What I have to do? Why getDeclatingClass () returns null, but in dejasmin code
it returns Outer class?Outer$Inner naming convention is not used by JVM to get declaring class.
You need to have proper InnerClasses attribute (refer to http://java.sun.com/docs/books/vmspec/2nd-edition/html/ClassFile.doc.html#79996)
in the generated classes. Did you check using jclasslib or another class file viewer and verified that your .class files have proper InnerClasses attribute? -
Dealing with abstract classes and interfaces with XMLBeans
I'm quite new to XMLBeans and would like some help. I've got things working when
you are only saving concreate classes as XML, but when it comes to clesses containing
interfaces I am running into problems.
I basically have a collection of XY objects (see below) that I want to save as
XML.
I want to convert the following java classes to an xml schema:
public class XY{
X x;
Y y;
public interface X{
void setA(int a);
int getA();
public interface Y{
void setB(int b);
int getB();
public class X1 implements X{
void setA(int a);
int getA();
//other data to save
public class X2 implements X{
void setA(int a);
int getA();
//other data to save
public class Y1 implements Y{
void setB(int b);
int getB();
//other data to save
public class Y2 implements Y{
void setB(int b);
int getB();
//other data to save
What would be the best way to convert these to XML Schema? I've looked through
all the XMLBeans documentation, but it doesn't say anything about dealing with
interfaces/abstract classes. Is there anywhere else to look?
Thanks in advance,
AndrewAnurag,
What I really wanted was a work-around to using substiutionGroups as substitution
groups are not supported in this release.
I want to convert the following schema:
<xsd:complexType name="PublicationType">
<xsd:sequence>
<xsd:element name="Title" type="xsd:string"/>
<xsd:element name="Author" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
<xsd:element name="Date" type="xsd:gYear"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="BookType">
<xsd:complexContent>
<xsd:extension base="PublicationType" >
<xsd:sequence>
<xsd:element name="ISBN" type="xsd:string"/>
<xsd:element name="Publisher" type="xsd:string"/>
</xsd:sequence>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
<xsd:complexType name="MagazineType">
<xsd:complexContent>
<xsd:restriction base="PublicationType">
<xsd:sequence>
<xsd:element name="Title" type="xsd:string"/>
<xsd:element name="Date" type="xsd:gYear"/>
</xsd:sequence>
</xsd:restriction>
</xsd:complexContent>
</xsd:complexType>
<xsd:element name="Publication" type="PublicationType"/>
<xsd:element name="Book" substitutionGroup="Publication" type="BookType"/>
<xsd:element name="Magazine" substitutionGroup="Publication" type="MagazineType"/>
<xsd:element name="BookStore">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="Publication" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
to produce an XML file like:
<?xml version="1.0"?>
<BookStore ¡Ä>
<Book>
<Title>Illusions: The Adventures of a Reluctant Messiah</Title>
<Author>Richard Bach</Author>
<Date>1977</Date>
<ISBN>0-440-34319-4</ISBN>
<Publisher>Dell Publishing Co.</Publisher>
</Book>
<Magazine>
<Title>Natural Health</Title>
<Date>1999</Date>
</Magazine>
<Book>
<Title>The First and Last Freedom</Title>
<Author>J. Krishnamurti</Author>
<Date>1954</Date>
<ISBN>0-06-064831-7</ISBN>
<Publisher>Harper & Row</Publisher>
</Book>
</BookStore>
What is the best way to do this without using substitution types?
Thanks,
Andrew
"Anurag" <[email protected]> wrote:
Andrew,
Could you please paste/attach a sample of the code you are using to convert
Java bean classes to XMLBeans?
In the current release the goal of XMLBeans technology was to convert
from
XML Schemas or XML files to XMLBeans. The focus was not towards conversion
of Java beans to XMLBeans.
Regards,
Anurag
"Andrew" <[email protected]> wrote in message news:[email protected]...
I'm quite new to XMLBeans and would like some help. I've got thingsworking when
you are only saving concreate classes as XML, but when it comes toclesses
containing
interfaces I am running into problems.
I basically have a collection of XY objects (see below) that I wantto
save as
XML.
I want to convert the following java classes to an xml schema:
public class XY{
X x;
Y y;
public interface X{
void setA(int a);
int getA();
public interface Y{
void setB(int b);
int getB();
public class X1 implements X{
void setA(int a);
int getA();
//other data to save
public class X2 implements X{
void setA(int a);
int getA();
//other data to save
public class Y1 implements Y{
void setB(int b);
int getB();
//other data to save
public class Y2 implements Y{
void setB(int b);
int getB();
//other data to save
What would be the best way to convert these to XML Schema? I've lookedthrough
all the XMLBeans documentation, but it doesn't say anything about dealingwith
interfaces/abstract classes. Is there anywhere else to look?
Thanks in advance,
Andrew -
Problems with loading Classes from a Directory of a jar file.
Hi Guys,
i have a problem with my programm. It works greatly in my eclipse platform. but there are all classes in my default folder. I want to add a plugin function now. My Abstract classes are in in my default folder and my doughter classes are in my plugin-folder called plugin.
I look what is in the pluginfolder -> all my doughter classes. but i every time get a Class Cast Exception and an ClassNotFoundException.
How can i do that ? Current i do it with Class.forName(frames.substring(0,frames[i].indexOf(".class")));
best regards flohttp://java.sun.com/j2se/1.3/docs/tooldocs/win32/classpath.html
-
Problem with JFrame class.
To risolve my problem i need for few diferent frame
( for esample in one i put JTextFild that take the user input, in a nother one i need for program output ) . But, th problem is, all my frames using the same object.
If i construct diferent JFrame window class i have problem that i don't acess in the same object from all the window. And if i dont use a object, i have static acess .
I risolve the problem with 1 JFrame class with diferent constructors, but i wont a diferent way to risolve my problem, because there are few windows.
Help me.....Make the class that extends JFrame an inner class of the the main class. You can then access all members of the outer class.
-
Problem compiling Abstract class
Hi
I have writting an abstract class Sort.java and another class BubbleSort.java. I am having problems compiling BubbleSort.java class.
The following is the error message
BubbleSort.java:8: missing method body, or declare abstract
public int doSorting(int[] array);
^
BubbleSort.java:11: return outside method
return num;
^
The following is the code
public abstract class Sort
public abstract int doSorting(int[] array);
}// End of class
public class BubbleSort extends Sort
private int num = 2;
public int doSorting(int[] array);
num = num + 2;
return num;
} // end of classRemove the semi-colon.
public int doSorting(int[] array); // <------- there -
Problems with importing classes in Java
Hello,
i have some problems with a simple project.
The structure is like this:
web-inf/classes/databeans/loginexistinguserform.java
web-inf/classes/formactions/loginexistinguseraction.java
loginexistinguserform.java :
package databeans;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
public class LoginExistingUserForm extends ActionForm
String userid;
String password;
public String getUserid(){return userid;}
public void setUserid(String newUserid){userid=newUserid;}
public String getPassword(){return password;}
public void setPassword(String newPassword) {password=newPassword;}
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request){
ActionErrors errors=new ActionErrors();
if(this.userid==null||this.userid.equals(""))
errors.add("user",new ActionError("error.userid.required"));
if(this.password==null||this.password.equals(""))
errors.add("pass",new ActionError("error.password.required"));
return errors;
}loginexistinguseraction.java
package formactions;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import databeans.LoginExistingUserForm;
public class LoginExistingUserAction extends Action
public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
LoginExistingUserForm loginData=(LoginExistingUserForm)form;
if(loginData.getUserid().equals("Admin")&&loginData.getPassword().equals("Parola"))
return mapping.findForward("successLogin");
else
return mapping.findForward("failureLogin");
}I can complie succesfully loginexisitinguserform.java but problems appears when i want to compile the second file, loginexistinguseraction.java with command: javac loginexistinguseraction.java
C:\ApacheGroup\Tomcat\webapps\PersonalWeb\WEB-INF\classes\formactions>javac loginexistinguseraction.java
loginexistinguseraction.java:10: package databeans does not exist
import databeans.LoginExistingUserForm;
^
loginexistinguseraction.java:17: cannot find symbol
symbol : class LoginExistingUserForm
location: class formactions.LoginExistingUserAction
LoginExistingUserForm loginData=(LoginExistingUserForm)form;
^
loginexistinguseraction.java:17: cannot find symbol
symbol : class LoginExistingUserForm
location: class formactions.LoginExistingUserAction
LoginExistingUserForm loginData=(LoginExistingUserForm)form;
^
3 errors
I have the CLASSPATH variable setup tu C:/Sun/Appserver/lib/j2ee.jar
Can someone help me ? Thank you in advance !Thank you very much ! It worked. I'm really new in Jav a programming.
Now i have encoutered another problem. When i want to login, and enter user name and password i am redirected to a login.do page, instead of Welcome.jsp
Here is Login.jsp:
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@page contentType="text/html; charset=ISO-8859-1"%>
<html>
<head><title>Login Form</title></head>
<body>
<html:errors/>
<html:form action="/login">
<table border="0" width="200">
<tr>
<td>User Name:</td>
<td><html:text property="userid" maxlength="13"/></td>
</tr>
<tr>
<td>Password:</td>
<td><html:password property="password" maxlength="13"/></td>
</tr>
</table>
<br />
<html:submit value="Login"/>
</html:form>
</body>
</html>and here is struts-config.xml :
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
<!--========================beans for HTML form data=======================-->
<form-beans>
<form-bean name="loginBean" type="databeans.LoginExistingUserForm"/>
</form-beans>
<!--========================Action Mappings================================-->
<action-mappings>
<action path="/login" type="formactions.LoginExistingUserAction" name="loginBean" input="/Login.jsp" scope="session">
<forward name="succesLogin" path="/pages/Welcome.jsp" redirect="true"/>
<forward name="failureLogin" path="/pages/Diverse.jsp" redirect="true"/>
</action>
</action-mappings>
<message-resources parameter="MessageResources" />
</struts-config> -
Problem with PriorityBlockingQueue Class(theory)
hi i came across a doubt which i cannot understand.
the PriorityBlockingQueue(PBQ) extends AbstrachQ(AQ) and implements BlockingQueue(BQ). now if u see both AQ and BQ have add methods and some other common code which does the same work is this not redundant. if not then in the PBQ which (for eg) add method are we overriding. also why could not a single interface/abstract class be sufficient for this instead of having one abstract class and one interface. i really cannot understand why the design has been done like this. can someone help.
thanksThe overrides in PBQ are just there to update the Javadoc comments with statements about blocking or priority. All they do is call e.g. super.add().
I don't understand your doubts about the design. It seems rather elegant to me. Queue defines the interface; AbstractQueue provides common operations to all implementations; and PBQ provides the priority mechanism and the blocking semantics for that particular implementation.
I do this sort of thing all the time. -
Reflection problem with private class
I am trying to write a junit on private class and I am stuck not knowing how to access private class.
Here is the structure of my code:
public abstract class cars extends auto{
private class model{
String name;
String year;
String make;
private model getInfo(name, year, make{
Model mod = new Model();
mod.name = "Echo";
mod.year = "1992";
mod.make = "Toyota";
return mod;
}Basically how do I use reflection so I can write assert such as
assertEquals(getInfo.year, "1992");Thanks in advance!You don't. Private methods, members, and classes are considered implementation details and should not be directly tested with your unit tests.
-
Problems implementing abstract classes
hello.
this is james mcfadden. I am developing a multiplayer BlackJack card game in Java. the game consists of three programs: BlackJack.java, BlackJackServer.java and BlackJackClient.java (three 3 programs are shown below). i don't know how to implement abstract classes. i am trying to get the BlackJack.java program working with the BlackJackServer.java program. there should be "extends BlackJackServer" somewhere in the BlackJack.java program, but i don't know where.
import javax.swing.*;
public class BlackJack extends JPanel{
public BlackJack(){
//FlowLayout is default layout manager for a JPanel
add(new JButton("Hit"));
add(new JButton("Stay"));
add(new JButton("New Game"));
public static void main(String[] args){
JFrame frame=new JFrame("BlackJack");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setLocation(200,200);
BlackJack bj=new BlackJack();
frame.setContentPane(bj);
frame.setVisible(true);
import java.io.*;//Provides for system input and output through data streams, serialization and the file system
import java.net.*;//Provides the classes for implementing networking applications
import java.util.*;//Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes
import java.awt.*;//Contains all of the classes for creating user interfaces and for painting graphics and images
import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
public class BlackJackServer extends JFrame{
private JTextArea jta=new JTextArea();//a text area for displaying text
public static void main(String[] args){
new BlackJackServer();//invokes the constructor BlackJackServer()
}//end main
public BlackJackServer(){
setLayout(new BorderLayout());//places the text area on the frame
add(new JScrollPane(jta),BorderLayout.CENTER);//lays out a text area, arranging and resizing its components to fit in the centre region;and provides a scrollable view of a lightweight component
setTitle("BlackJack Server");//Sets the title for this frame to the specified string
setSize(500,300);//Resizes this component so that it has a width and a height
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Sets the operation that will happen by default when the user closes this frame
setVisible(true);//shows the frame
try{
ServerSocket serverSocket=new ServerSocket(8000);//creates a server socket
jta.append("Server started at "+new Date()+'\n');//displays the current date in the text area
Socket socket=serverSocket.accept();//listens for a connection request
DataInputStream inputFromClient=new DataInputStream(socket.getInputStream());//creates a data input stream
DataOutputStream outputToClient=new DataOutputStream(socket.getOutputStream());//creates a data output stream
while(true){
float bet=inputFromClient.readFloat();//receives bet from the client
float doublebet=bet+bet;//computes double the bet
outputToClient.writeFloat(doublebet);//sends double the bet back to the client
jta.append("Bet received from client: "+bet+'\n');//displays the bet in the text area
jta.append("Double the bet found: "+doublebet+'\n');//displays double the bet in the text area
}//end while
}//end try
catch(IOException ex){
System.err.println(ex);//displays an error message
}//end catch
}//end constructor
}//end class BlackJackServer
import java.io.*;//Provides for system input and output through data streams, serialization and the file system
import java.net.*;//Provides the classes for implementing networking applications
import java.awt.*;//Contains all of the classes for creating user interfaces and for painting graphics and images
import java.awt.event.*;//Provides interfaces and classes for dealing with different types of events fired by AWT components
import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
public class BlackJackClient extends JFrame{
private JTextField jtf=new JTextField();//a text field for receiving text
private JTextArea jta=new JTextArea();//a text area for displaying text
private DataOutputStream toServer;//output stream
private DataInputStream fromServer;//input stream
public static void main(String[] args){
new BlackJackClient();//invokes the constructor BlackJackClient()
public BlackJackClient(){
JPanel p=new JPanel();//holds the label and text field
p.setLayout(new BorderLayout());//sets the layout of the content pane of this component by default
p.add(new JLabel("Enter bet"),BorderLayout.WEST);//displays the bet and lays out a JLabel, arranging and resizing its components to fit in the western region
p.add(jtf,BorderLayout.CENTER);//lays out the text field, arranging and resizing its components to fit in the centre region
jtf.setHorizontalAlignment(JTextField.RIGHT);//Sets the horizontal alignment of the text to the right
setLayout(new BorderLayout());//places the text area on the frame
add(p,BorderLayout.NORTH);//lays out the text field, arranging and resizing its components to fit in the northern region
add(new JScrollPane(jta),BorderLayout.CENTER);//lays out a text area, arranging and resizing its components to fit in the centre region;and provides a scrollable view of a lightweight component
jtf.addActionListener(new ButtonListener());//invokes the ButtonListener class
setTitle("BlackJack Client");//Sets the title for this frame to the specified string
setSize(500,300);//Resizes this component so that it has a width and a height
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Sets the operation that will happen by default when the user closes this frame
setVisible(true);//shows the frame
try{
Socket socket=new Socket("localhost",8000);//creates a socket to connect to the server
fromServer=new DataInputStream(socket.getInputStream());//creates an input stream to receive data from the server
toServer=new DataOutputStream(socket.getOutputStream());//creates an output stream to send data to the server
}//end try
catch(IOException ex){
jta.append(ex.toString()+'\n');//displays an error message
}//end catch
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
float bet=Float.parseFloat(jtf.getText().trim());//gets the bet from the text field
toServer.writeFloat(bet);//Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream
toServer.flush();//Flushes this output stream and forces any buffered output bytes to be written out
float doublebet=fromServer.readFloat();//gets double the bet from the server
jta.append("Bet is "+bet+"\n");//displays the bet in the text area
jta.append("Double the bet received from the server is "+doublebet+'\n');//displays double the bet in the text area
}//end try
catch(IOException ex){
System.err.println(ex);//displays an error message
}//end catch
}//end method
}//end class
}//end class BlackJackClientthere should be "extends BlackJackServer" somewhere in the BlackJack.java programI very much doubt that.
It's possible you might need to create a BlackJackServer object or something like that. But I don't see the point in subclassing it. -
Mixing polymorphism with abstract classes???
Hi,
Can you have polymorhism with abstract superclasses in Java?
For example, say I have a superclass called Pet:
abstract class Pet {
private String name;
public String getName() {
return name;
public void setName(String petName) {
name = petName;
public String speak() {
return "I am a Pet";
}Now I have a Cat subclass:
public class Cat extends Pet{
public String speak {
return "i am a cat";
public class Dog extends Pet {
public String fetch() {
return "fetching a stick";
}In my test method I have:
public class TestPet {
public static void main(String[] args) {
Pet p = new Pet();
System.out.println(p.speak());
Pet p = new Dog();
System.out.println(((Dog)p).fetch());
Pet p = new Cat();
System.out.println(p.speak() +" is now a cat");
}So it appears to me that you cannot have polymorphic methods with an abstract superclass - is this right?
Cheers.cotton.m wrote:
List<Pet> pets = new ArrayList<Pet>();
I was working (more or less) along the same lines...
package forums;
import java.util.List;
import java.util.ArrayList;
abstract class Pet
private String name;
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
public String speak() {
return "I am a Pet";
public abstract String fetch(); // <<<<< the new bit.
public String getClassName() {
final String name = this.getClass().getName();
return name.substring(name.lastIndexOf('.')+1).toLowerCase();
class Cat extends Pet
public Cat(String name) {
setName(name);
public String speak() {
return "I am a cat";
public String fetch() {
return "No. I am a cat!";
public String rollOver() {
return "No. I am a cat!";
class Dog extends Pet
public Dog(String name) {
setName(name);
public String fetch() {
return "Look boss, I'm fetching the stick.";
public String sit() {
return "Look boss, I'm sitting!";
public class PetTest
public static void main(String[] args) {
List<Pet> pets = new ArrayList<Pet>();
pets.add(new Cat("Fungus"));
pets.add(new Dog("Spike"));
for ( Pet pet : pets ) {
System.out.println("\""+pet.speak()+"\" said "+pet.getName()+" the "+pet.getClassName()+".");
System.out.println("\"Go fetch\" said the master.");
System.out.println("\""+pet.fetch()+"\" said "+pet.getName()+".");
System.out.println();
System.out.println("Therefore we conclude that dogs are much better pets.");
}Both these examples demonstrate that polymorphism is very useful when we have a list of different-type-if-things which have a common interface... i.e. different classes which have (a) a common ancestor; or (b) a common interface... allowing us to treat those different types-of-things as if they where one-type-of-thing, except the-different-types actually do different stuff internally, which is appropriate-to-there-specific-type.
That's the essence of polymorphism... and, of course, this seperation of "type" and "implementation" isn't limited to lists-of-stuff... it can be very useful all over the show.
Cheers. Keith.
Edited by: corlettk on 10/05/2009 11:01 ~~ That's a bit clearer. -
Problem with loading classes!!!
I am loading classes using
// Open File
InputStream jarFile = new BufferedInputStream(new FileInputStream(
pluginPath));
// Get Manifest and properties
Attributes attrs = new JarInputStream(jarFile).getManifest().
getMainAttributes();
jarFile.close();
// Read Main Class
String mainClass = attrs.getValue("Protocol-Class");
// Load all classes from jar file without giving classpath
URL url = new URL("jar:file:" + pluginPath + "!/");
JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
URL[] urls = new URL[] {
url};
ClassLoader classLoader = new URLClassLoader(urls);
// Create new instance of protocol
Protocol protocol = (Protocol) classLoader.loadClass(mainClass).
newInstance();
I am loading classes one by one say a order A, B, C. In my case class c extends class A. So I am loading class A first and later B and finally C. But I am getting exceptions when loading class C that Class A is unknown.The following exception is thrown
java.lang.NoClassDefFoundError: com/a/A at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:537)
Please give me a solution to make it run.You create a new class loader for each class. The class loaders are independent, and so the class hierarchies they load are independent. Class A loader by classLoaderOne doesn't see class B loader by classLoaderTwo - they are loaded into their own sandboxes.
Either load everything with one class loader or create the class loaders in a hierarchy. To create a hierarchy use the class loader constructor that takes a parent class loader as a parameter. One class loader may be easier because then you don't need to worry about loading order. -
Object oriented design problem concerning abstract classes and interfaces
I have an abstract class (class A) that takes care of database connections. It cannot be made into an interface as other classes extend it and all these other classes require the functionality in the methods it has (i.e. I cannot make all the methods abstract and then make this class an interface).
I have a class that contains data (Customer class) that I will create from the data I extract from the database. This class will also be created by the User and submitted to the database portion of the program. The Customer class has functionality in its methods which is required by the rest of the program (i.e. I cannot make all the methods abstract and then make this class an interface).
I have a factory class (CustomerFactory) that extends the Customer class. This has been created to restrict access to the creation and manipulation of Customers.
I have a class (DatabaseQuery) that extends class A. But now that I have retrieved all of the information that comprises a Customer from the database, I cannot construct a Customer without making reference to UserFactory. But UserFactory is a class that I don't want the database portion of the program to know about.
What I would like to do is have my DatabaseQuery class extend both Customer class and A class. But they are both classes and Java won't allow that.
I can't make either of the two classes that I want to make parents of DatabaseQuery into interfaces... so what can I do other than just keep a reference to UserFactory in my DatabaseQuery class?
Thanks,
Tim>
What I would like to do is have my DatabaseQuery class
extend both Customer class and A class. But they are
both classes and Java won't allow that.
I can't make either of the two classes that I want to
make parents of DatabaseQuery into interfaces... so
what can I do other than just keep a reference to
UserFactory in my DatabaseQuery class?Just a guess...
The description sounds a little vague but it sounds like the correct solution would be to refactor everything. The first clue is when I see "database connection" as an "abstract class". The only hierarchy that a database connection might exist in is in a connection pool and even that is probably shaky. It should never be part of data records, which is what your description sounds like.
That probably isn't what you want to hear.
The other solution, which is why refactoring is better (and which also makes it apparent why the original design is wrong) is to create an entire other hierarchy that mirrors your current data hierarchy and wraps it. So you now have "Customer", you will now have "Customer" and "DBCustomer". And all the code that currently uses "Customer" will have to start using DBCustomer. Actually it is easier than that since you can simply make the new class be "Customer" and rename the old class to "DBCustomer". Naturally that means the new class will have to have all of the functionality of the old class. Fortunately you can use the old class to do that. (But I would guess that isn't going to be easy.)
Maybe you are looking for
-
HT4623 I did the update to my iPhone 4 and I loose my voice memos how can I recover them?
I did the update to my iPhone 4 and I loose my voice memos how can I recover them?
-
Hi, all, If I've got an PL/SQL region that dynamically generates a form using HTMLDB_ITEM.TEXTAREA, what is the best way to get the contents of those form data at submit time? Thanks, Don Message was edited by: Don_84 Edited for clarity.
-
Advice on Security Model Architecture..
Hi all, Just looking for the advice of the experts :) I am working on the security model architecture for multi-tiered java application. The application architecture breaks down roughly as follows: Presentation Layer (JSP/Java) Business Layer (Java)
-
No matter how many times I provide my Keychain Password, the pop-up window keeps coming back. Seriously annoying...I'd rather not use Keychain. Any way to just turn this crap off?
-
Apex is too slow to login and run report
Hello Expert, I am working to fix a problem with APEX is extremely slow to login. It might take 3 to 5 min for the login to show up and it takes forever to load the reports on the screeen that has 1000's of rows. And when it comes to clik on the butt