I'm studying Swing in Java at first.
above thing is correct and another thing is incorrect code.
Correct
public class Example extends JFrame{
public Example() {
}
Incorrect
public class Example extends JFrame{
public Othor() {
}
Despite it's not Constructor, why function name should be same with class name?
I am not sure what you mean with "Despite it's not Constructor" - in the first snippet, public Example() is a constructor, means it will be executed when the object is created with new Example(). In the second snippet, public Othor() would be a normal method of the class, even though it is missing the return type, so this does not compile (this is probably the error message you get, something like Return type is missing).
The correct code for the second snipped would be something like
public class Example extends JFrame{
public void othor() {
}
}
(note that methods usually start with a non-capital letter). In this case, a default constructor would implicitly be created, but void othor() is a normal method of the class.
Also note that this is just normal Java behaviour, and completely independant of Swing or any other toolkit or framework.
See also Purpose of a constructor in Java?
Related
I am working on creating a java utils library and have come across a problem with generics. I have found a solution that lets the library work, but it seems like bad code practice and prone to undetected program failures. For question's sake, I've simplified the program into a minimum verifiable example.
Let's say I have an interface Invokable<E>, which is called upon to effect an E.
public interface Invokable<E> {
void invoke(E e);
}
Let's say I have another interface, InvokableFactory<E>, which creates Invokable<E>s
public interface InvokableFactory<E> {
Invokable<E> create();
}
Now let's say I have a class InvokableUser<E>, that is designed to be extended. It holds an InvokableFactory<E>, and uses it to create an Invokable<E>, which it then invokes with itself.
public class InvokableUser<E> {
private InvokableFactory<E> factory;
public InvokableUser(InvokableFactory<E> factory) {
this.factory = factory;
}
public void start() {
factory.create().invoke((E) this);
}
}
You might see that my conundrum is that I'm trying to ensure that a subclass InvokableUser, extends InvokableUser of the generic type of itself. I'm trying to ensure that an InvokableUser contains a factory that produces Invokables that can be invoked with the InvokableUser object, but still be passed an object of the type of the subclass of InvokableUser so that the Invokable can utilize methods added only by the subclass of InvokableUser.
I feel like I might not be explaining this very well, so for example, let's say there's a subclass of Invokable that needs to print out the getString method added by a subclass of InvokableUser, like this:
public class PrintingInvokable implements Invokable<PrintingInvokableUser> {
#Override
public void invoke(PrintingInvokableUser e) {
System.out.println(e.getString());
}
}
public class PrintingInvokableUser extends InvokableUser<PrintingInvokableUser> {
public PrintingInvokableUser() {
super(PrintingInvokable::new);
}
public String getString() {
return "( ͡° ͜ʖ ͡°)";
}
}
If you create a new PrintingInvokableUser() and call start() on it, it will create a new PrintingInvokable() and call invoke(this) on it, when will then print out the getString() method of the PrintingInvokableUser.
While my code does work for this, it depends on the unwritten expectation that a subclass Foo of InvokableUser will extend InvokableUser<Foo>, involves an unchecked cast which is bad (and raises a compiler warning), seems to not even make use of the generic type as I could achieve the same effect with unparametrized types, and generally seems like there has to be a better way to do this.
If someone could point me in the right direction for how to do this, I'd be appreciative. Thanks!
I am trying to use a protected static method in the Lucene information retrieval api. My understanding of static is that they are accessed from the class definition and my understanding of the protected keyword is that they can only be accessed from instances of that class or the subclass. So how exactly do you access a static protected method? Is my understanding mistaken? I am trying to call a protected static method from a library in an imported jar. How would I do that?
In this case I am calling the loadStopwordSet from StopwordAnalyzerBase
Why can't you call this method by referring to it as StopwordAnalyzerBase.loadStopwordSet(params) ?
Consider this example (which compiles and works on my machine):
package p1;
public class C1 {
protected void nonStatic() {}
protected static void isStatic() {}
}
----
package p2;
import p1.C1;
public class C2 extends C1 {
public void someMethod() {
super.nonStatic();
C1.isStatic(); // or even C2.isStatic()
}
}
Getting back to your original question, I can see that this method is called from within ArabicAnalyzer:78 (Lucene version 4.9.0, package org.apache.lucene.analysis.ar) as well as many others.
The "Base" part of the class name should give you a hint: this is meant to be called from a subclass of StopwordAnalyzerBase
It is static because it need not be an instance method (it is self-contained and does not alter the state of the object that calls it). Looking at the API doesn't tell me why it would be protected, though - apart from following the minimum privilege principle, I suppose
I have been coding for few days with swing, but im getting to a problem ...I have functions and variables from different classes that are set in the main class that runs the program and calls the jframe.The problem i have is how do i call the functions in the main class in the jframe code that is set as a new class named as
public class login_sistema extends javax.swing.JFrame
I have tried puting the methods from main as static methods still i cant call the methods this way ...If you could help me i would be appreciated ...
I have tried puting the methods from main as static methods still i cant call the methods this way ...If you could help me i would be appreciated ...
Static methods are the last thing you should be using. It sounds like you want to have one object call the methods of another object, and to do that the first object must have a valid reference to the second object. This can be achieved by passing it through the first object's constructor parameter or via a setXXX(...) method.
For instance if the first object creates the second object, it could pass a reference to itself, this into the second object's parameter. e.g.,
The MainClass:
public class MainClass {
private OtherClass otherClass;
public MainClass() {
otherClass = new OtherClass(this);
}
}
the OtherClass:
public class OtherClass {
public MainClass mainClass;
public OtherClass(MainClass mainClass) {
this.mainClass = mainClass;
}
public void someOtherClassMethod() {
// now we can call methods with the MainClass reference
mainClass.someMainClassMethod();
}
}
For more details on your particular problem, consider telling us more about it and showing code.
Is there any way to forbid the son class to call the public method of super class in java?
For example
public abstract class TObject{
abstract public void quark();
}
public class Animal extends TObject{
public void quark(){
System.out.println("this is the animal");
}
}
public class Dog extends Animal{
#overide
public void quark(){
System.out.println("this is the animal");
**super.quark();**
}
}
In this example, The Dog call the **super.quark();** in it's quark method.
But I don't want the Dog could call super.quark(); and I also don't want to change the
modifier of quark method in Animal to private. Is there any way to prevent this in compile?
I have be confused couple of days, who can help me........
The reason I do that is I met the similar problem in developing hudson scm plugin.I
created the class which extends the SubversionSCM(the offical class). I just wanted to
override the public method of super class, then call super's public method back like
example. but the compile gave error.I don't konw why, how could it do? Dose java have
something like reflect ways to prevent this?
No, by definition of public you can't stop the method from being called (whether from a derived class or anywhere else). You can of course stop it from being overridden (and thereby ensure that the syntax used to call it won't use super;-) by making it final.
No, there's no way to have a public method that subclasses can't call. The best you can do is document this recommendation.
As a note, it's called a subclass or child class.
The other 2 answers (Alex & Matthew) are basically right.
you can prevent the subclass from calling a public method from the super class
there is probably something wrong with your design if you do this.
The below Father class has two public methods named fatherMethod. Subclasses can call the fatherMethod using reflection (Thank You Matthew for pointing that out.) Without using reflection, subclasses can probably not call either fatherMethod method. Thus it is very similar to a private method.
class Father
{
private class Alpha { }
private class Beta { }
public void fatherMethod ( Alpha param )
{
}
public void fatherMethod ( Beta param )
{
}
}
I Have something similar to this setup:
public class Base {
public String getApple() {return "base apple"};
}
public class Extended extends Base{
public String getApple() {return "extended apple"};
}
Somewhere else in the code I have this:
{
Base b = info.getForm();
if (b instanceof Extended){
b = (Extended) b;
}
System.out.println(b.getApple()); // returns "base apple" even when if clause is true why??
}
How do I accomplish that?
First:
if (b instanceof Extended){
b = (Extended) b;
}
does absolutely nothing. You are basically saying b = b, which says nothing. You are not even changing the reference.
Second, getApple() will always be dynamically bound, and the "extended apple" should always be called - given that the subclass is truly extending the base class, and the method is truly overridden.
Basically what you need to do, in order to accomplish correct getApple() behavior:
remove the if clause. it does nothing.
make sure your class is indeed extending the base class
make sure the getApple() method is overriding the base class method. (use the #override annotation if you are not sure)
As written, your code will not compile, which makes me think that your problem is elsewhere. Your return statements don't have semicolons at the end of them. Rather, they appear after the }. It's possible you had some other problem (maybe your subclass misspelled getApple()), but you're still using your old class files because your new stuff isn't compiling.
This code works:
class Base {
public String getApple() { return "base apple"; }
}
class Extended extends Base {
public String getApple() { return "extended apple"; }
}
public class Test {
public static void main(String[] args) {
Base b = new Extended();
System.out.println(b.getApple());
}
}
Console:
#javac Test.java
#java Test
extended apple
First of all, that if block should never be necessary. It's basically a no-op.
Second, this isn't your real code, because it doesn't even compile. You're missing semicolons after the return statements.
I suspect that your problem is that your real code has a typo that's making the signatures of the two getApple methods different. This means that Extended has two methods: the one inherited from Base and the one with a different signature in itself. Since you're calling with the signature of the Base.getApple method, you're always getting that behavior. This is only a guess though, as your posted code does not exhibit the problem you describe.
Yuval is right that your cast in the if block has no effect. You might try combining your last statement with the if:
if (b instanceof Extended)
{
// Prints "extended apple" if reached.
System.out.println(((Extended)b).getApple());
}
Add #Override to the method in your subclass and recompile. This will help you find out if you're not actually overriding the method you think you are.
i.e.
public class Base {
public String getApple() {return "base apple";}
}
public class Extended extends Base{
#Override
public String getApple() {return "extended apple";}
}
The only way to get that behavior is to return super.getApple() in your extended class, which is effectively the same as not overriding it in the first place. The only way this could help is if you pass in an argument to decide which to return. Not saying thats good design...
Forgot to mention that, as Yuval said, the cast does nothing to the object.
You should investigate what is constructing your instance that is returned from info.getForm(). You may want to make the Base abstract to prevent it from being instantiated and you'll quickly see where construction is happening.
Are you sure your code example provided in your question EXACTLY matches the code your are using? The reason I ask is that the behavior you are describing happens when you access a public FIELD instead of a public METHOD with an object pointer.
For example:
public class BaseClass {
public String baseField;
public BaseClass() {
baseField = "base";
}
public String getBaseField() {
return baseField;
}
}
public class SubClass extends BaseClass {
public String baseField;
public SubClass () {
baseField = "sub";
}
public String getBaseField() {
return baseField;
}
}
public class MainClass {
public static void main(String[] args) {
BaseClass baseObject = new BaseClass();
SubClass subObject = new SubClass();
System.out.println(baseObject.getBaseField());
System.out.println(subObject.getBaseField());
System.out.println(baseObject.baseField);
System.out.println(subObject.baseField);
System.out.println(((BaseClass)subObect).getBaseField());
System.out.println(((BaseClass)subObect).baseField);
}
}
Will print out:
base
sub
base
sub
sub
base
When you call a method, the JVM will start at the bottom of the inheritance hierarchy and call the appropriate method. When you reference a field instead, it uses the class of the pointer instead of walking up the class hierarchy to resolve the value. The behavior of the field reference matches what you're seeing, which is why I ask for clarification/verification.