Hi friends im learning java from basics..
I have some doubt in implementing interface.
WORKING CODE
Using interface in a class is working....
interface bala
{
void prnt();
}
class ex implements bala{
#Override
public void prnt() {
System.out.print("hi");
}
}
public class Solution
{
public static void main(String arg[])
{
ex p = new ex();
p.prnt();
}
}
NOT WORKING
Here is my doubt, why i cant implement interface in main method?
plea
interface bala
{
void prnt();
}
public class Solution implements bala
{
public static void main(String arg[])
{
prnt();
}
#Override
public void prnt() {
System.out.println("hi");
}
}
What is happening here?
Why implementing on main() is not working?
Is there is a way to make working interface on main function?
Given Bellow code works well.
interface bala
{
void prnt();
}
public class Solution implements bala
{
public static void main(String arg[])
{
Solution sol = new Solution();
sol.prnt();
}
public void prnt() {
System.out.println("hi");
}
}
It's not working, because you're trying to access non-static (i.e. instance) method from a static context.
In order to invoke it, you need an instance of the Solution class (note that in your working code you have an instance of the ex class, so here you need to do the same with slight difference):
Solution instance = new Solution();
instance.prnt();
Problem is main() is static, static blocks can access static members or with object reference . So here you could simply create an object/instance to invoke the method:
new Solution().prnt();
try new Solution().prnt() instead of calling prnt()
the problem is :
main method is a static method. And your overridden method is non-static. You can't call non-static methods from static context.
In order to call overridden method prnt() to call, you need to instantiate you Solution class like -
Solution sol = new Solution();
and then
sol.prnt();
Best Option to Do it . Create the instance of class and Access it.since main method is a static method you can do like that
Solution instance = new Solution();//Creating instance of class
instance.prnt();//access prnt .
You should create the object of Solution class in main method
Solution s1 = new Solution();
s1.print();
Otherwise, you can create the method as static because you are trying to access
the method from static context.
Related
I would like to access one variable that is a part of my GUI class. Should I instantiate my GUI class outside of that GUI class? Right now it is instantiated inside of main which I believe makes it inaccessible for me.
So is the best way to access variables in this class to instantiate this object in a different class and in that class create getters and setters for it?
public class NormalDistributionUI extends JFrame {
public static void main(String args[]) {
new NormalDistributionUI().setVisible(true);
}
}
Should it be like e.g.
public class Main {
static NormalDistributionUI ndUI;
public NormalDistributionUI getndUI() {
return ndUI;
}
public static void main(String args[]){
ndUI = new NormalDistributionUI();
}
}
EDIT: a different idea
public class NormalDistributionUI extends JFrame {
static NormalDistributionUI ndUI;
public static void main(String args[]) {
ndUI = new NormalDistributionUI()
ndUI.setVisible(true);
}
}
Does that make more sense than creating a separate class?
It depends on what you want. The second alternative would work as well, assuming that you called the method setVisible somewhere else.
The difference between the two of them is that in the second case the GUI object will be named and, hence, accessible afterwards. In the first case, it is anonymous.
You don't need a whole separate class. The first one is fine. If you want to manipulate the NormalDistributionUI object, you can use a local variable.
public class NormalDistributionUI extends JFrame {
public static void main(String args[]) {
NormalDistributionUI ndUI = new NormalDistributionUI();
ndUI.setSomeProperty(foobar);
ndUI.setVisible(true);
}
}
Basicly what i am asking is this:
public void RunMe(Method method){
}
so basicly i mean if i can run the Method called "method" from that Method called RunMe(Method....
Use a Method as an argument isn't the right way.
Hum the best way (I think) to do something like that is to use the reflection.
Example:
public void RunMe(Object target, String methodName){
Class c = target.getClass();
Method m = c.getMethod(methodName, new Class[0]);
m.invoke(target, new Object[0]);
}
If you need more details about it you can check here.
If you want to access a method outside its class, the method cannot be a private method. If you don't know what private, public, static, etc. is, read about access-level modifiers.
Let's say that you have a class called MyClass with a method called myMethod, and your main() in a class called MainClass then you would do it like this:
class MyClass {
static void myMethod() {
System.out.println("Testing");
}
}
public class MainClass {
public static void main(String[] args) {
foo();
}
void foo() {
MyClass.myMethod();
}
}
myMethod has to be static if you want to reach the method without creating an object of MyClass. However, you might dislike static and have no problem with creating an object. In that case, do something like this:
class MyClass {
void myMethod() {
System.out.println("Testing");
}
}
public class MainClass {
public static void main(String[] args) {
foo();
}
void foo() {
MyClass a = new MyClass();
a.myMethod();
}
}
public class StaticInnerClass {
public static void main(String[] args) {
//Outers out=new Outers();
Outers.Inner1 in=new Outers.Inner2();
in.display();
}
}
class Outers
{
static class Inner1
{
static void display()
{
display();
System.out.println("Inner1");
}
}
static class Inner2 extends Inner1
{
static void display()
{
System.out.println("Inner2");
}
}
}
The above program gives a stackoverflow error. Please explain that why doesn't it display "Inner1" because static methods don't override.
The static method that executes is based on the static type, not the instance type:
Outers.Inner1 in=new Outers.Inner2();
So when you call this line, the static type is Outers.Inner1 and therefore it calls the display method that's part of this class, which calls itself repeatedly (causing the StackOverflowError.)
Static methods are not invoked polymorphically!
This will cause the method display to invoke itself again and again until you get Stack Overflow Error. Also, see this question : Polymorphism and Static Methods
A static method can't be overridden by sub class
Static methods should be called with Class not with an object, even though you use object, it still going to use the type of the object.
This question already has answers here:
Static Classes In Java
(14 answers)
Closed 3 years ago.
So, in short. I have two classes.
package rpg;
public class Engine {
public void main(String args[]) {
Start.gameStart();
System.out.println(menuResult);
}
}
and
package rpg;
public class Start {
int menuResult = 3;
public int gameStart()
{
return menuResult;
}
public int getMenuResult()
{
return Start.menuResult;
}
}
It keeps throwing up the error 'Cannot make static reference to non-static method gameStart()'.
I'm sure I'm missing something simple, but can't find it.
Thanks!
You need to create instance of Start class and call gameStart() method on that instance because gameStart() is instance method not static method.
public void main(String args[]) {
new Start().gameStart();
..................
}
Only static methods can be accessed by using class name as perfix.
public int gameStart() <--- Instance method not static method
call it on instance
Start start = new Start();
start.gameStart();
So finally your classes should look like below
public static void main(String args[]) {
Start start = new Start();
start.gameStart();
System.out.println(start.getMenuResult());
}
public class Start {
private int menuResult = 3;
public int gameStart() {
return this.menuResult;//Don't know why there are two methods
}
public int getMenuResult() {
return this.menuResult;
}
}
first of all the main method should be
public static void main(String args[]) {
}
I assume you can have multiple games, and hence you should be able to start multiple instances so you should create a non static class that can be created and then actions performed against.
to answer your original question, you need to have a static variable that have static getters and setters..
public class Start {
private static int menuResult = 3;
public static int gameStart()
{
return menuResult;
}
public static int getMenuResult()
{
return Start.menuResult;
}
If you need the method to be static, just add the keyword static in the function definition. That would get rid of the error. But if you want to keep the class Start the way it is, then you should create an instance of Start in the main function and then call the method. Hope that helps!
you are trying to invoke a method on its class name. you should be creating a new object and invoke its method
public void main(String args[]) {
new Start().gameStart();
System.out.println(menuResult);
}
Start.gameStart() refers to a method which would be public static int gameStart() because Start is the class and not an instance of the object.
If you declare a method on an object, you need to apply it to instance of the object and not its class.
When to use static or instanciated methods ?
instanciated : whenever you need to apply the method to the object you're in. example : mycake.cook();
static : when the actions you do inside your method have nothing to do with an object in particular. example : Cake.throwThemAll();
mycake is an instance of a Cake, declared this way : Cake mycake = new Cake();
Cake is the class representing the object.
You should, i guess, have a read at some object oriented programmation course if you still have a doubt about objects, classes and instances.
While Other answers are Correct , that remains the Question that Why you Can't access Instance
method Directly from Class name , In Java all static (methods , fields) bind with Class Name and when Class Is Loading to the Memory (Stack) all static members are Loading to the Stack , and this time Instance Method is not visible to Class. instance Method will Load into Heap portion in the memory and can only be access by Object references .
I want to make a convenient super class that will make an instance of whatever subclass it is ran from, without having to hard-code the name of the sub class. What is the fastest way to do this?
We can assume that the subclasses' constructors will have same signature, e.g. no parameters.
class Main {
public static void main (String [] args) {
Main m = new NAME-OF-SUBCLASS();
}
}
class MainSub1 extends Main { /*...*/ }
class MainSub2 extends Main { /*...*/ }
So when invoking main from MainSub1 ($ java MainSub1 from the command line), a MainSub1 object is created, etc.
As I wrote this, i found this thread where the accepted answer says it can't be done, but of course it can, somehow, through reflection or something, right?
Not that I'd really recommend it, but there's a dirty trick to it:
class Main {
static Main m;
public static void main (String [] args) {
// use m
}
}
class MainSub1 extends Main { static { m = new MainSub1(); } }
class MainSub2 extends Main { static { m = new MainSub2(); } }
A serious answer would be to write a separate main for each subclass, but let it call a common inherited method that accepts an appropriate instance.