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.
Related
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?
Is there any way I can trigger class constructor automatically while extending from the class?
I have a class TestSet.java
public class TestSet {
public TestSet(String name) {
Logger.msg("Test set: " + name);
}
}
And I would like for the constructor to trigger every time that I extend from this class.
It seems that I need to call the constructor "manually" with:
public class TC1SendAnEmail extends TestSet{
//I have to type this every single time again and again...
//---------------------------------------------------------
public TC1SendAnEmail(String name) {
super(name);
}
//---------------------------------------------------------
public void run() {
new EmailLogin().run();
...
}
}
Which I would like to avoid. (Because I will be creating possibly hundreds/thousands of those extended classes.)
From what I have managed to research, I guess that this function is not implemented in Java. But it just seems weird that I would have to "copy-paste" the constructor again, again and again...
Maybe there is another solution that I dont see? (Maybe without even using the constructor to "do something every time an instance of a class that extends my TestSet class is created".)
EDIT:
Yes, I can see why you think that creating hundreds/thousands of subclasses is wrong. I am creating a big automation project. Every class of this type will be a "test". And there will be thousands of tests...
EDIT#2:
The point of this question was that I needed to trigger the superclass constructor every time I extend from it. My mistake was adding parameter to the superclass constructor. If you donĀ“t add a parameter to the constructor, then it is triggered automatically while extending.
From your comments I kinda understand what you're trying to achieve. (Automatically printing the name of the current running test)
So what about the following snippet:
public class TestSet {
public TestSet(){
Logger.msg("Test set: " + getClass().getSimpleName());
}
}
This baseclass just prints the name of the implementing class when it is created. E.g. when using the following class:
public class TC1SendAnEmail extends TestSet {
// your methods
}
it prints:
Test set: TC1SendAnEmail
This works, because in java the default constructor (constructor with no arguments) of the superclass doesn't have to be overridden, because the compiler will generate it automatically.
Yes.
Otherwise, how will it know that you want to pass name into it and not some other parameter?
What you can do is replace this copy-paste code with some sort of Template method pattern:
public class SO50215241 {
public abstract static class TestSet {
public TestSet() {
System.out.println("Test set: " + getName());
}
abstract String getName();
}
public static class TC1SendAnEmail extends TestSet{
#Override
String getName() {
return "TC1Name";
}
}
public static void main(String[] args) {
new TC1SendAnEmail();
}
}
Prints:
Test set: TC1Name
Then you can try to extend some specific version of TestSet for concrete implementations instead of extending TestSet itself.
Or calculate name dynamically inside getName method body.
Let's say I have a class 'Person' and another class 'Survey' which extends person so Survey is the child class and Person class is the parent. Person was the first class I wrote and hence defined the main method there now since I have a child class, can I call methods of the child class from the main method in the parent class (or do I need to keep transferring the main method to the class that is lower most in the heirarchy although I am pertty sure this is never ever going to be necessary...)? If so is this not counter intuitive to the notion that the child class inherits attributes of the parent class but the parent class does not inherit any attributes of the child class? Please do oblige with a reply. Thanks in advance.
Also I also read another post of having a separate class maybe 'driver.java just for the main method so would this mean that all classes would have to be imported into this class for us to call methods from other class in the main method?
I hope my question is not too convoluted.
Let me explain it to you,
When you create an instance of the Subclass by calling new on the sub class type, then immediately its Super class constructor is called, and it keeps going till the Object class, this is called Constructor chaining.
All the instance variable are declared and initialized during this process.
And most important is that when constructor of subclass it called it goes to its super class and so on till the Object class, then 1st creating the Object class object, then the class under it, till it reaches the subclass on whose class new was called, You will see that the constructor of the super class is called first then its subclass's
And for your above question i have also created an example which fits appropriately with the theoretical explanation i have given.
eg:
public class a {
public static void main(String[] args) {
B b = new B();
b.go();
}
}
class B extends a{
public void go(){
System.out.println("hello");
}
}
Well I tried it out and it does work fine even if I put the main method in the parent class. But I have done some reading and the observed practice is to create the main method in a separate class such that the class has only the main method in it and no other methods. This improves efficiency in some cases and is a much cleaner way of donig things.
You can call method of class B from class a only by creating object of class B in class a, if you do not want to use inheritance.
You can't call method of class B through class a from object of class a without using inheritance.
public class a {
public static void main(String[] args) {
B b = new B();
b.go();
}
}
class B {
public void go(){
System.out.println("hello");
}
}
Using inheritance:
//calling method of class B by using object of class a.
public class a extends B {
public static void main(String[] args) {
a b = new a();
b.go();
}
}
class B {
public void go(){
System.out.println("hello");
}
}
I came across this scenario. We have a class lets say Main having a private method print. There is another class Main1 which extends Main class and redefines the print method. Since main1 is an object of Main1 class, I expect main1 print method to get called...
public class Main {
public static void main(String[] args) {
Main main1 = new Main1();
List<String> list = new ArrayList<String>();
main1.print(list);
}
private void print(List<String> string) {
System.out.println("main");
}
}
class Main1 extends Main {
public void print(List<String> string) {
System.out.println("main1");
}
}
In this case, when we run the program, it print "main". It really confuses me as that method is private and is not even part of Main1 class.
The answer is not too hard:
the type of the main1 variable is Main (not Main1)
so you can only call methods of that type
the only possible method called print that accepts a List<String> on Main is the private one
the calling code is inside the class Main so it can call a private method in that class
Therefore Main.print(List<String>) will be called.
Note that changing the type of main1 to Main1 will result in the other print(List<String>) method being called.
If you want to be able to override your print method you have to declare it public:
public class Main {
public void print(List<String> string) {
}
}
Otherwise it will call your private method without looking for the implementation in a derived class .
Private method is not inherited and method overriding does not happened in your code.
You can see this by putting #Override annotation in Main1.print() method. If you put that annotation, compile error generated.
Main.java:17: method does not override or implement a method from a supertype
#Override
^
1 error
In your case, Main1.print() and Main.print() are different and not related each other(no overriding, no overloading). So if you specify main1 as Main, Main.print() will be called. And if you specify main1 as Main1, Main1.print() will be called.
Your main1 is a type of Main but instantiated with as Main1! It's OK since it is a subclass for Main. However, when you call the print method (BTW, it should be main1.print(list);) it will call the private method in the Main class! If you change the visibility of your method to protected or public, in this case print method in the Main1 class will be called because of polymorphic behavior of your instantiated object (remember, it is after all a Main1 object based on the code that you've provided!)
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 )
{
}
}