Problem of super class.
Hi all,
I am adding a menuItem to a menu of a menuBar which the menu has a old menuItem. The
requirement is that the old menuItem of the menu only enable in the main window and disable in the others, and the new menuItem only disable in the main window and enable in the others. The problem is that this menu class is a super class, the main class extends from it which coordinate all the other panels(windows). So when I try to enable the new menuItem in the others windows, I modified the super class, then it enable in the main window as well which is wrong. I don't allowed to modify the basic structure of the project.
Any ideas? Thanks a lot!
Please help!
Similar Messages
-
Javah problem - super class could not be found !!
Hi all,
i have already posted this message but i didn't get enough help to solve my poor situation.
and this is my problem:
i got in my project (myProject) MyClass class.
i wrote in another java class ,in OtherClass.class ,jni function that use MyClass object as parameter to the jni interface, as follow:
private native int myFunction (MyClass obj); //function in OtherClass
when i write the javah command line :
javah -jni OtherClass (in order to create OtherClass.h)
i always get the following error:
A required super class myPackage.MyClass could not be found.
my qoustion is how can i let the javah command line to know about the existence of myPackage.MyClass and how can i create and .h file when i using other class instance as jni function parameter in other class??
Thanks Sendy.Lets define a few terms here.
Java can be a java virtual machine which is what runs when you type 'java' on the command line. It is also represented by the compiler which runs when you type 'javac'. And in your case it also is represented by 'javah'.
The class path defines where java finds classes that it needs.
In older versions of java you had to tell it where to find everything. It couldn't even find java.lang.String unless you told it were it was. Now days you have to tell it where to find stuff that you add (or where 3rd party libraries are.)
There are two ways to define the class path: a command line option and an environment variable.
A class path can, currently, have three types of things in it:
-A path to a zip file
-A path to a jar file
-A path
For example
-Path to zip file in windows: C:\mystuff\mylib\mystuff.zip
-Path to zip file in unix: /opt/system/projects/mystuff/mystuff.zip
-Path to jar file in windows: C:\mystuff\mylib\myjar.jar
-Path to jar file in unix: /opt/system/projects/mystuff/myjar.jar
-Path in windows: C:\mystuff\mylib
-Path in unix: /opt/system/projects/mystuff
Zip files aren't used as much anymore, but you should at least be aware of them.
Java uses the class path to look for classes which are stored in files. It does this by translating the class name into a file name. It uses packages as directory names and class names as file names. So in your case it would try to find a class called myPackage.MyClass in a file called myPackage\MyClass.class. It would try to find that in any zip files, jar files, in in any paths that you specified in the class path.
So java is trying to find myPackage\MyClass.class in your class path. It would try to find that in any zip files, jar files, in in any paths that you specified in the class path.
Right now your class path is probably just "." which means that if you do the following commands
cd C:\mystuff
javah -jni OtherClass
Then java is going to try to find myPackage.MyClass in the following file
.\myPackage\MyClass.class
That, because you 'cd' to C:\mystuff, translates to the following absolute path
C:\mystuff\myPackage\MyClass.class
So if java doesn't find that file then it is going to tell you that it can't find the file.
So where is your file? Let's say it is here.
C:\work\lib\myPackage\MyClass.class
So you must tell javah where the root is. Keep in mind that 'myPackage' must be part of the path. That is not optional. The root is the directory above 'myPackage'. So the root is
C:\work\lib
So now you have a path that is ready for your class path. So your javah command could look like this
javah -classpath ".;C:\work\lib" -jni OtherClass
Or using an environment variable
set CLASSPATH=.;C:\work\lib
javah -jni OtherClass
Keep in mind in the above that class path is a generic term and there can be other ways to define it. For example the Sun command "java" allows you to use "-classpath" or "-cp".
So does the above help? -
Problem with subclass and super class
here is the things i wanted to do
/*Write a method that takes the time as three integer arguments (hours, minutes and seconds),
and returns the number of seconds since the last time it was twelve o'clock.
Write a program that uses this method to calculate the amount of time in seconds between two times,
assuming both are within one twelve hour cycle of a clock.
here is a class to find the last time closes to 120'clock in sec.
import java.io.*;
public class Timer {
int converter = 60;
int secinTwelveHour = 43200;
int converter2 = 12;
public int timerTime (int hour, int min, int sec){
int totalSec = 0;
//Finding the time
if (hour > 0 && hour <= 24 && min > 0 && min <=60 && sec > 0 && sec <= 60 && hour <= 11){
//find last 12 o'Clock
hour = converter2 + hour;
//change to sec time
totalSec = (hour * converter * converter) + (min * converter) + sec;
}else{
if (hour > 0 && hour <= 24 && min > 0 && min <=60 && sec > 0 && sec <= 60 && hour >= 12){
//find last 12 o'Clock in sec
totalSec = ((hour * converter * converter) + (min * converter) + sec) - secinTwelveHour;
}else{
return -1;
}//End of return -1
}//End of first else statment
return totalSec;
}//End of timerTimer
}//End of Program
and here is the super class which uses the class aboved
import java.io.*;
public class FindTime {
public int find2Time (int totalSec1, int totalSec2){
int timeSec = 0;
if(Timer.totalSec1 > Timer.totalSec2)
timeSec = Timer.totalSec1 - Timer.totalSec2;
else
timeSec = Timer.totalSec2 - Timer.totalSec1;
return timeSec;
}//End of find2Time
public static void main( String [] arg){
// Construct an instance of the Timer class
Timer timerClass = new Timer();
// Make a couple of calls of the method
int totalSec1 = timerClass.timerTime(12, 3, 45);
int totalSec2 = timerClass.timerTime(14, 23, 60);
timeSec1 = find2Time (totalSec1, totalSec2)
// Now print the values we got back
System.out.println("Last closes Sec to 12 o'clock" + totalSec1);
System.out.println("Last closes sec to 12 o'clock" + totalSec2);
System.out.println("Last closes sec to 12 o'clock" + timeSec);
}//End of main method
}//End of Program
Now i'm having program with the compliing can anyone help me out like tell me what i'm doing wrong and give me a bit of a code so that i can have a push start
thanks youDoes this do what you want? It is in two seperate classes.
import java.io.*;
public class FindTime {
public static void main( String [] arg){
int timeSec = 0;
// Construct an instance of the Timer class
Timer timerClass = new Timer();
// Make a couple of calls of the method
int totalSec1 = timerClass.timerTime(12, 3, 45);
int totalSec2 = timerClass.timerTime(14, 23, 60);
timeSec = java.lang.Math.abs(totalSec1-totalSec2);
// Now print the values we got back
System.out.println("Last closes Sec to 12 o'clock " + totalSec1);
System.out.println("Last closes sec to 12 o'clock " + totalSec2);
System.out.println("Last closes sec to 12 o'clock " + timeSec);
}//End of main method
}//End of Program
import java.io.*;
public class Timer {
int converter = 60;
int secinTwelveHour = 43200;
int converter2 = 12;
public int timerTime (int hour, int min, int sec){
int totalSec = 0;
//Finding the time
if (hour > 0 && hour <= 24 && min > 0 && min <=60 && sec > 0 && sec <= 60 && hour <= 11){
//find last 12 o'Clock
hour = converter2 + hour;
//change to sec time
totalSec = (hour * converter * converter) + (min * converter) + sec;
} else {
if (hour > 0 && hour <= 24 && min > 0 && min <=60 && sec > 0 && sec <= 60 && hour >= 12){
//find last 12 o'Clock in sec
totalSec = ((hour * converter * converter) + (min * converter) + sec) - secinTwelveHour;
} else {
return -1;
}//End of return -1
}//End of first else statment
return totalSec;
}//End of timerTimer
}//End of Program -
Nor any of its super class is known to this context ...problem
hi all
i have simple complex object in jave that looks like this :
@XmlAccessorType(XmlAccessType.FIELD)
public class MyID{
@XmlAttribute
public short dbnum = (short)0;
@XmlAttribute
public short usernum= (short)0;
@XmlAttribute
public long userid = (long)0;
public MyId(){
}i converted it with jaxb and it generete me corespanding java object with the propreate geters and seters
now when i try to in the server side to insert this object into List<Object> im geting error saing :
Caused by: javax.xml.bind.JAXBException: com.WebServices.datastructures.MyID nor any of its super class is known to this context
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getBeanInfo(JAXBContextImpl.java:474)
at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:557)
... 47 more
i must say that if i send back only this object (MyID) the unmarsheling passed successfully
thanks for your helpOk I found it out
jboss was using the jre default axis impelmentation while the server where my client was deployed was using the axis 2 implementation
I changed the server to use jre default axis and things worked now
Thanks
Sapan -
Calling a method from a super class
Hello, I'm trying to write a program that will call a method from a super class. This program is the test program, so should i include extends in the class declaration? Also, what code is needed for the call? Just to make things clear the program includes three different types of object classes and one abstract superclass and the test program which is what im having problems with. I try to use the test program to calculate somthing for each of them using the abstract method in the superclass, but its overridden for each of the three object classes. Now to call this function what syntax should I include? the function returns a double. Thanks.
Well, this sort of depends on how the methods are overridden.
public class SuperFoo {
public void foo() {
//do something;
public void bar(){
//do something
public class SubFoo extends SuperFoo {
public void foo() {
//do something different that overrides foo()
public void baz() {
bar(); //calls superclass method
foo(); //calls method in this (sub) class
super.foo(); //calls method in superclass
}However, if you have a superclass with an abstract method, then all the subclasses implement that same method with a relevant implementation. Since the parent method is abstract, you can't make a call to it (it contains no implementation, right?). -
Calling a particular Method of all subclass from a super class
hi
I have a class 'A' which is a super class for 'B' ,'C' , 'D'
my main method is in the class Main and while on the run i am calling methods of B,C,D form this main class.
but as the first step of execution i need to call a init method which has been defined in all the sub-classes. and there can be any no of sub-classes and all will have the init method and i have to call the init method for all classes. is this possible to do that in runtime. ie i wil not be knowing the names of sub-classes.
thanks
zetaSorry if i had mislead you all.
I am not instantiating from my super class.
as mjparme i wanted one controller class to do the
init method calls
so i got it working from the link you gave.
URL url = Launcher.class.getResource(name);
File directory = new File(url.getFile());
This way i can get all the classes in that
in that package
and from reflection i can get whether it is
her it is a sub class of the particular super class
and i can call the init methods by making the init
methods static
thanks for the help
zetaThis is a rather fragile solution.
If the problem is one of knowing which subclasses exist, I would suggest specifying them explicitly via configuration (system property or properties file or whatever).
One thing that's not entirely clear to me: Is the init going to be called once for each subclass, or once for each instance of each subclass? It sounds to me like it's once per class, but I want to make sure. -
Weird one.. i can't return a variable from the extended to the super class
Hey everyone, i hope i'm not annoying you guys :)
So today's problem is to return a variable (int) from a method of the extended class and print it ont the super class.
I'm just testing the super class , if it works fine.
So the extended class ( FileIO) just read the file txt and return the integer or string ( from the txt file)
I already did a main method to that class and tested it, it works fine.
So now the problem is to print the integer ( that the extended class gets from the txt. ) inside the Super class. I mean , is the same thing but now im testing the Super class , just have to do the same thing, a super class method calls the extended class method and receive the integer from the txt file.
i think the problem is when i create the instance of the FileIO object , maybe its constructor ...i don't know.
The name of the txt file is passed from the super class to the extended class, but i think the error is not from there.
this.aero_le = new BufferedReader(new FileReader(super.ficheiroleitura_aero())); // super calls ficheiroleitura_aero() and receive the name of the txt file ( e.g "temp.txt") so i think that is correct.
here's the code of the Super class public class Aeroporto {
private String filereader_voo = "temporary.txt";
private String filereader_aero = "temp.txt";
private String siglaAero = "";
public FileIO file;
public Aeroporto(){};
public Aeroporto(String filereader_voo, String filereader_aero) throws IOException{
this.filereader_voo = filereader_voo;
this.filereader_aero =filereader_aero;
file = new FileIO();
public String siglaAero() {
return siglaAero; }
public String filereader_aero(){
return filereader_aero;
public int nrLines() throws IOException{ // it was supose to retunr the number of lines ( integer) from the txt file .
return Integer.parseInt(file.lerLinhaN(1,1));
// main() {
Aeroporto a = new Aeroporto();
int v = a.nrLines();
System.out.print(v);
// ***********************************************************+
// Extended Class
public class FileIO extends Aeroporto{
private String ficheiroescrita;
private PrintWriter vooescreve, aeroescreve ;
private BufferedReader voo_le, aero_read;
public FileIO(){}
public FileIO(String filereader_voo, String filereader_aero, String ficheiroescrita) throws IOException {
super(filereader_voo, filereader_aero);
this.ficheiroescrita = ficheiroescrita;
//If file does not exists , create one.
try{
this.aero_read = new BufferedReader(new FileReader(super.filereader_aero()));
aero_read.close();
catch(IOException ex){
this.aeroescreve = new PrintWriter(new FileWriter(ficheiroescrita));
aeroescreve.close();
public String lerLinhaN(int line, int column) throws IOException{ // this method works fine , i already tested this class.
this.aero_read = new BufferedReader(new FileReader(super.filereader_aero()));
for(int i = 0; i != line-1; ++i) aero_read.readLine();
String linha = aero_read.readLine();
String [] words = linha.split(" ");
return words[column-1];
Maybe the error is that i use to test the Super class a default contructor on both classes... i don't know where the error is, i also did two small classes ( super and another that extends ) and get the string "Hello" from the super and print it inside the extended..and it works, that's why i think the error is when i call the extended class .. need help.
thanks.Ok,
This one might actually work... atleast it compiles.import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;
public abstract class FileIO {
public static boolean CreateOutputFileIfNotExists(
String outputFilename //the name of the file to ensure exists.
) throws IOException
final String functionName = "FileIO.CreateOutputFileIfNotExists";
boolean retVal = false;
//If the output file does does not exist then create it.
//post condition: output file exists or an IOException has been thrown.
BufferedReader infile = null;
try{
infile = new BufferedReader(new FileReader(outputFilename));
retVal = true;
} catch(IOException ex) {
PrintWriter outfile = null;
try {
outfile = new PrintWriter(new FileWriter(outputFilename));
retVal = true;
} catch(IOException ex2){
throw new IOException(functionName + ": cannot create output file " + outputFilename, ex2);
} finally {
outfile.close();
if (outfile.checkError()) {
throw new IOException(functionName + ": error on output stream " + outputFilename);
} finally {
try {
infile.close();
} catch(IOException ex){
throw new IOException(functionName + ": cannot close output file " + outputFilename, ex);
return(retVal);
public static String readLine(
String inputFilename //the name of the file to read.
, int lineNumber //1 based number of the line to read from.
) throws IOException
final String functionName = "FileIO.readLine";
String outputLine = null;
// reads the numbered "lineNumber" from "inputFilename".
BufferedReader infile = null;
try {
infile = new BufferedReader(new FileReader(new File(inputFilename)));
for(int i=1; i<lineNumber; ++i) infile.readLine();
outputLine = infile.readLine();
} catch(IOException ex){
throw new IOException(functionName + ": cannot read input file " + inputFilename, ex);
} finally {
try {
infile.close();
} catch(IOException ex){
throw new IOException(functionName + ": cannot close input file " + inputFilename, ex);
return(outputLine);
public static String readWord(
String inputFilename //the name of the file to read.
, int lineNumber //1 based number of the line to read from.
, int wordNumber //0 based number of the word to read.
) throws IOException
final String functionName = "FileIO.readWord";
String outputWord = null;
// reads the numbered space-seperated "wordNumber" from the numbered "lineNumber" of "inputFilename"
try {
String[] words = FileIO.readLine(inputFilename, lineNumber).split(" ");
if (wordNumber>0 && wordNumber<words.length) outputWord = words[wordNumber-1];
} catch(IOException ex){
throw new IOException(functionName + ": cannot read input file " + inputFilename, ex);
return(outputWord);
}Design notes... FileIO is a generic helper class... there is nothing specific to Airports, flights, or any other "domain" specific stuff in it... so it's re-usable... you can keep it and reuse it on other projects, or even share it with your friends.
So... The airport class will just call the static methods on FileIO like this ....
int lineNumber=1;
int wordNumber=1;
String airportCode = FileIO.readWord(airportsFilename, lineNumber, wordNumber);
....How's that?
corlettk: my now mandatory edit. -
Generic interface in abstract super class
hello java folks!
i have a weird problem with a generics implementation of an interface which is implemented in an abstract class.
if i extend from this abstract class and try to override the method i get this compiler error:
cannot directly invoke abstract method...
but in my abstract super class this method is not implemented as abstract!
do i have an error in my understanding how to work with generics or is this a bug in javac?
(note: the message is trown by the eclipse ide, but i think it has someting to do with javac...)
thanks for every hint!
greetings daniel
examples:
public interface MyInterface <T extends Object> {
public String testMe(T t);
public abstract class AbstractSuperClass<T extends AbstractSuperClass> implements MyInterface<T> {
public String testMe(T o) {
// do something with o...
// now we have a String str
return str;
public final class SubClass extends AbstractSuperClass<SubClass> {
@Override
public String testMe(SubClass o)
return super.testMe(o);
}Hi Wachtda,
Firstly, T extends Object is redundant as all classes implicitly extend the Object class.
Therefore :
public interface MyInterface <T> {
public String testMe(T t);
}Secondly, abstract classes may have both abstract and non-abstract instance methods. Also, two methods, one abstract and one non-abstract, must have a different signature.
The following example will give a compile error because the methods share the same signature :
abstract class Test {
public void sayHello() {
System.out.println("Hello");
abstract public void sayHello();
}Therefore, to make an interface method as abstract would simply block the possibility of implementing it.
BTW, you can do this :
abstract class Test {
public void sayHello() {
System.out.println("Hello");
abstract public void sayHello(String name);
}Finally, there's no bug in javac. -
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? -
How to indicate the object of the super Class ?
hello,
I need to notify when one dialog is close to the class that generated it.
Of course I do it from the method windowClosing() in the class WindowAdapter.
But if I use "this" how parameter in the method, I noted the value is that of the inner anonymous class, and not that of the dialog class.
I write down some code to reproduce the problem ....
public ReferenceToTheSuperClass() {
final SecondClass sc = new SecondClass(this);
jButton1 = new javax.swing.JButton();
// final ReferenceToTheSuperClass xx = this;
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sc.checkSuper(xx); // work
sc.checkSuper(this); // not work
sc.checkSuper(super.getClass()); // not work
} // ReferenceToTheSuperClass
class SecondClass {
ReferenceToTheSuperClass superiorClass;
public SecondClass(ReferenceToTheSuperClass supClass){
superiorClass = supClass;
public void checkSuper(Object o){
if (o instanceof ReferenceToTheSuperClass){
JOptionPane.showMessageDialog(null,"HELLO");
} // SecondClass My ask is: It is possible to indicate the value of the instance of the super Class, inside one his anonynimous inner class?
thank you
regards
tonyMrsangelothank you for your kinkly answer jeverd,
yes what you say is right, in this case the class is only nested (in the hurry I used a wrong word).
About the sintax, I vould find only a short statement to use inside the inner anomymous class and, reading what you say, I can guess it is not possible to do it..
again thank you
regards
tonyMrsangelo -
How to pass subclass to variable of super class ?
class /EVUIT/EXCH_PRD_GUI definition
public section.
methods CONSTRUCTOR
importing
value(I_APPLICATION) type ref to /UIT/EXCH_PRD_APP optional
value(I_REPID) like SY-REPID .
class /UIT/EXCH_PRD_VERT_NN_MODEL definition
public
inheriting from /EVUIT/EXCH_PRD_APP
create public .
DATA: l_vert_nn_model type ref to /uit/exch_prd_vert_nn_model.
DATA: l_gui type ref to /uit/exch_prd_gui_vbeleg.
CREATE OBJECT l_vert_nn_model
EXPORTING
I_ALV_RECORDS = gt_alv_records[].
CREATE OBJECT l_gui
EXPORTING
I_APPLICATION = l_vert_nn_model
I_REPID = sy-repid .{color}
Problem i am facing is for l_gui the parameter i_application is of type super class of l_vert_nn_model.
Any suggestions, how can i pass this subclass object to the parameter which is of type super class?Hello Trivenn
On SAP basis release 7.00 the following coding works:
*& Report ZUS_OO_DUMMY
REPORT zus_oo_dummy.
* CLASS lcl_local DEFINITION
CLASS lcl_local DEFINITION.
PUBLIC SECTION.
METHODS:
constructor
IMPORTING
value(io_instance) TYPE REF TO zcl_edi_uk_svcs_out. " super class
PRIVATE SECTION.
data: mo_instance type ref to object.
ENDCLASS. "lcl_local DEFINITION
* CLASS lcl_local IMPLEMENTATION
CLASS lcl_local IMPLEMENTATION.
METHOD constructor.
mo_instance ?= io_instance.
ENDMETHOD. "constructor
ENDCLASS. "lcl_local IMPLEMENTATION
DATA: go_super TYPE REF TO zcl_edi_uk_svcs_out,
go_sub TYPE REF TO zcl_edi_uk_svcs_out_customer,
go_local type ref to lcl_local.
START-OF-SELECTION.
CREATE OBJECT go_super.
CREATE OBJECT go_sub.
create object go_local
exporting
io_instance = go_sub.
BREAK-POINT.
END-OF-SELECTION.
Regards
Uwe -
Hi,
I have created one class in SE24. This class will be used as a super class for other classes.
When subclasses are derived from this superclass, i want to make sure that some of the methods of superclasses are redefined by the subclasse compulsarily.
So i want to force the subclasses to redefine complusarily some of the methods of its super class.
Is this feasible. If so please let me know the corresponding approach.
Thanks in advance !
PramodHi,
Check this out this will help you.
Inheritance is the concept of passing the behavior of a class to another class.
1.You can use an existing class to derive a new class.
2.Derived class inherits the data and methods of a super class.
3.However they can overwrite the methods existing methods and also add new once.
4.Inheritance is to inherit the attributes and methods from a parent class.
Inheritance:
Inheritance is the process by which object of one class acquire the properties of another class.
Advantage of this property is reusability.
This means we can add additional features to an existing class with out modifying it.
Go to SE38.
Provide the program name.
Provide the properties.
Save it.
Provide the logic for inheritance.
*& Report ZLOCALCLASS_VARIABLES *
*&----------------------------------------------------*REPORT ZLOCALCLASS_VARIABLES.
*OOPS INHERITANCE
*SUPER CLASS FUNCTIONALITY
*DEFINE THE CLASS.
CLASS CL_LC DEFINITION.
PUBLIC SECTION.
DATA: A TYPE I,
B TYPE I,
C TYPE I.
METHODS: DISPLAY,
MM1.
CLASS-METHODS: MM2.
ENDCLASS.
*CLASS IMPLEMENTATION
CLASS CL_LC IMPLEMENTATION.
METHOD DISPLAY.
WRITE:/ 'THIS IS SUPER CLASS' COLOR 7.
ENDMETHOD.
METHOD MM1.
WRITE:/ 'THIS IS MM1 METHOD IN SUPER CLASS'.
ENDMETHOD.
METHOD MM2.
WRITE:/ 'THIS IS THE STATIC METHOD' COLOR 2.
WRITE:/ 'THIS IS MM2 METHOD IN SUPER CLASS' COLOR 2.
ENDMETHOD.
ENDCLASS.
*SUB CLASS FUNCTIONALITY
*CREATE THE CLASS.
*INHERITING THE SUPER CLASS.
CLASS CL_SUB DEFINITION INHERITING FROM CL_LC. "HOW WE CAN INHERIT
PUBLIC SECTION.
DATA: A1 TYPE I,
B1 TYPE I,
C1 TYPE I.
METHODS: DISPLAY REDEFINITION, "REDEFINE THE SUPER CLASS METHOD
SUB.
ENDCLASS.
*CLASS IMPLEMENTATION.
CLASS CL_SUB IMPLEMENTATION.
METHOD DISPLAY.
WRITE:/ 'THIS IS THE SUB CLASS OVERWRITE METHOD' COLOR 3.
ENDMETHOD.
METHOD SUB.
WRITE:/ 'THIS IS THE SUB CLASS METHOD' COLOR 3.
ENDMETHOD.
ENDCLASS.
*CREATE THE OBJECT FOR SUB CLASS.
DATA: OBJ TYPE REF TO CL_SUB.
START-OF-SELECTION.
CREATE OBJECT OBJ.
CALL METHOD OBJ->DISPLAY. "THIS IS SUB CLASS METHOD
CALL METHOD OBJ->SUB.
WRITE:/'THIS IS THE SUPER CLASS METHODS CALLED BY THE SUB CLASS OBJECT'COLOR 5.
SKIP 1.
CALL METHOD OBJ->MM1. "THIS IS SUPER CLASS METHOD
CALL METHOD OBJ->MM2.
*CREATE THE OBJECT FOR SUPER CLASS.
DATA: OBJ1 TYPE REF TO CL_LC.
START-OF-SELECTION.
CREATE OBJECT OBJ1.
SKIP 3.
WRITE:/ 'WE CAN CALL ONLY SUPER CLASS METHODS BY USING SUPER CLASS OBJECT' COLOR 5.
CALL METHOD OBJ1->DISPLAY. "THIS IS SUPER CLASS METHOD
CALL METHOD OBJ1->MM1.
CALL METHOD OBJ1->MM2.
This example will help you to solve your problem.
For more detailed information GOTO -> SAPTECHNICAL ->Tutorials -> Object Oriented Programming.
Regards Madhu.
Code Formatted by: Alvaro Tejada Galindo on Jan 7, 2009 12:13 PM -
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 :)
-
Instantiation of similar object over a super class deciding the sub class
Hello all
First, sorry if I'm duplicating an already answered question. I didn't searched very deep.
Initial position:
I have 2 Object (A1 and A2) which share the most (about 90%) of their instance variables an the associated methods. The values of the instance variables are retrieved in the real implementation from a stream. Depending of the data of the stream, I have to instantiate either a A1 or A2 object.
A test implementation (using an int in case of the stream):
The super class A:
package aaa;
public class A
protected int version = -1;
protected String name = null;
protected AE ae = null;
protected A()
protected A(int v)
// Pseudo code
if (v > 7)
return;
if (v % 2 == 1)
this.version = 1;
else
this.version = 2;
public final int getVersion()
return this.version;
public final String getName()
return this.name;
public final AE getAE()
return this.ae;
}The first sub class A1:
package aaa;
public final class A1 extends A
protected A1(int v)
this.version = v;
this.name = "A" + v;
this.ae = new AE(v);
}The second subclass A2:
package aaa;
import java.util.Date;
public final class A2 extends A
private long time = -1;
protected A2(int v)
this.version = v;
this.name = "A" + v;
this.time = new Date().getTime();
this.ae = new AE(v);
public final long getTime()
return this.time;
}Another class AE:
package aaa;
public class AE
protected int type = -1;
protected AE(int v)
// Pseudo code
if (v % 2 == 1)
this.type = 0;
else
this.type = 3;
public final int getType()
return this.type;
}To get a specific object, I use this class:
package aaa;
public final class AFactory
public AFactory()
public final Object createA(int p)
A a = new A(p);
int v = a.getVersion();
switch (v)
case 1:
return new A1(v);
case 2:
return new A2(v);
default:
return null;
}And at least, a class using this objects:
import aaa.*;
public final class R
public static void main(String[] args)
AFactory f = new AFactory();
Object o = null;
for (int i = 0; i < 10; i++)
System.out.println("===== Current Number is " + i + " =====");
o = f.createA(i);
if (o instanceof aaa.A)
A a = (A) o;
System.out.println("Class : " + a.getClass().getName());
System.out.println("Version : " + a.getVersion());
System.out.println("Name : " + a.getName());
System.out.println("AE-Type : " + a.getAE().getType());
if (o instanceof aaa.A2)
A2 a = (A2) o;
System.out.println("Time : " + a.getTime());
System.out.println();
Questions:
What would be a better way to encapsulate the logic into their respective objects ? Is there a way to let the super class A itself identify the type of the object and then extend from A to either A1 or A2 ?
Thanks in advance
AndreasHello jduprez
First, I would thank you very much for taking the time reviewing my problem.
Just for the record: have you considered regular serialization? If you control the software at both ends of the stream, you could rely on standard serialization mechanism to marshall the objects and unmarshall them automatically.In my case, I can't control the other site of the stream. At the end, the data comes from a FileInputStream and there aren't objects on the other site, only pur binary data.
- It seems you have one such factory class. Then you already have encapsulated the "determine class" logic, you don't need to add such logic in superclass A.I thought from an OO view, that the super class A is responsible of doing that, but that's where the problem starts. So at the end, it's better doing it in the factory class.
- A itself encapsulates the logic to load its own values from the stream.
- A1 and A2 can encapsulate the logic to load their own specific value from a stream (after the superclass' code has loaded the superclass' attributes values).
My advise would be along the lines of:
public class A {
.... // member variables
public void load(InputStream is) {
... // assign values to A's member variables
// from what is read from the stream.
public class A1 extends A {
... // A1-specific member variables
public void load(InputStream is) {
super.load(is);
// now read A1-specific values
public class AFactory {
public A createA(InputStream is) {
A instance;
switch (is.readFirstByte()) {
case A1_ID:
a = new A1();
break;
case A2_ID:
a = new A2();
break;
a.load(is);
}The example above assumes you have control over the layout of the data in the stream (here for a given A instance, the attributes defined in A are read first, then come the subclass-specific attributes.
The outcome is: you don't have to create a new A( ) to later create another instance, of a subclass.I like the idea. In the AFactory, is the "A instance;" read as "A a;" ?
Is there a way to let the super class A itself identify the type of the object and then extend from A to either A1 or A2 ?Note I initially read this question as "can an instance of a class mutate into another class", to which the answer is no (an object has one single, immutable class; it is an instance of this class, and of any superclass and superinterface, but won't change its class at runtime).Yes, I have been thinking about a way for mutating into a subclass to keep the already initialized values from the A class without copying or parsing again. But preventing an instance of an A class will be my way. So, in this aspect, Java didn't changed in the last 10 years... It's a long time ago I've used Java for some real projects.
You can, however, create an instance of another class, that copies the values off a priori A instance. Your example code was one way, another way could be to have a "copy constructor":
public class A {
public A(A model) {
this.att1 = model.att1;
this.att2 = model.att2;
public class A1 {
public A1(A model) {
super(model);
... // do whatever A1-specific business
)Still, I prefer my former solution less disturbing: I find the temporary A instance redundant and awkward.Nice to know. I prefer the first solution too.
Thank you again for the help and advices. My mind is searching sometimes for strange solutions, where the real is so close ;-)
Andreas -
Why isn't there a simpler way to initialize a subclass with its super class
Let me explain my doubt with an example...
public class Parent {
� public String parent;
public class Child extends Parent{
� public String child;
I've an instance of Parent p. I want to construct Child c, with the data in p.
The only way that is provided by Java language seems to be, having a constructor in Child like
public class Child extends Parent{
� public String child;
� public Child(Parent p){
� � parent = p.parent;
� }
The problem with this is there is lot of redundant assignment code.
What I don't understand is why there is not a simpler way of doing this when a subclass is after all super class data + some other data(excuse me for not looking at the bahavior part of it)
I'm looking for something as simple as Child c = p, which I know is wrong and know the reasons too.
Yes, we can wrap Child over Parent to do this, but it necessitates repeating all the methods in Parent.
Why is the language writers didn't provide a simple way of doing this? I should be missing something here...I'm just searching for an explanation. May be I'm asking a dumb question, but this bugs me a lot...
Regards,
Kothapalli.To answer DrClap, I'm demanding it now :-). Let me
not suggest something that Mr.Gosling didn't think of;
he should be having some reasons in not providing it.Because it's essentially impossible in the general case. One of the reasons you may be extending a class is to add new invariants to the superclass.
eg- extend java.awt.Rectangle by BoundedRectangle - extra invariant that none of its corner points may be less than 0 or more than 100 in any dimension. (The rectangle must be entirely contained in the area (0,0)-(100,100))
What would happen if you try to create a BoundedRectangle from a rectangle representing (50,50)-(150,150)? Complete invariant breakdown, with no generic way to handle it, or even recognise it.
Actually, BIJ and sgabie are asking for it. Provide an
automatic copy constructor. Every object should have
an implicit copy constructor defined. From any
subclass, I should be able to invoke
super(parentClass). From the subclass, we can invoke
super(parentClass) first and then go on to initialize the
subclass data.
I really don't know the implementation issues of this,
but what I'm looking for is something like this. I'm just
curious to know the implementation issues.Implementation issue #1: Classes that should not, under any circumstane, be copied.
* eg 1- Singleton objects. If there's an automatic copy constructor, then multiple singletons can be created, making them essentially useless. This by extension kills the Typesafe Enum pattern also.
* eg 2- Objects with extra information, such as java.sql.Connection - if you copied this, would the copy be using the same socket connection, or would another connection be required? What happens if opening another connection, and the JDBC driver requires the password to be entered for every new connection? If the wrong password is entered, what happens to the newly creating connection?
Implementation issue #2: Copying implementation?
* Already mentioned by RPWithey. The only guaranteed way to perform the copy would be with a shallow copy, which may end up breaking things.
Why can't you write the copy constructor yourself? If it's a special case, it only has to be done once. If it's a recurring case, you could write a code generation tool to write them for you, along with most of the rest of the class.
Maybe you are looking for
-
Hello all: Please help. New to this forum. Using Lightroom 2.2 on Mac. I had to do a restart after a freeze and then I got the message: The lightroom catalog named Lightroom 2 Catalog can not be opened because another application already has it opene
-
Addition to my earlier post on TV shows on Ipod, I have noticed lately, when I sync my Ipod, some of the files listed under TV shows, disappear from the Ipod, although they are still in Itunes, and NOT selected for deletion. Is this an extra feature
-
Aliasing when resizing 1080p to 720p
I can't wrap my head around this, maybe you can. Original source video: Prores 422 1920x1080 square pixels 29.97 Destination encoding: H.264 1280x720 square pixels 29.97 3000kbps When I do this, there is severe aliasing, especially on text. However i
-
Hello, I am generating a report in BEx Explorer I need to output Current date as Report date in my report output? Also My report input variables as follows 1.Period No 2.Fiscal Year But user want to see inthis order 1.Fiscal Year(Comming from RKF) 2.
-
How to install MySQL driver for ODI Studio?
Hi, I follow the docs to install driver. http://download.oracle.com/docs/cd/E14571_01/core.1111/e16453/install.htm#CHDBIFAJ First I downloaded MySQL Java connector from http://dev.mysql.com/downloads/connector/j/. Then copy the jar file to C:\Users\M