I am clearing my concepts on Java. My knowledge about Java is on far begineer side, so kindly bear with me.
I am trying to understand static method and non static method intercalls. I know --
Static method can call another static method simply by its name within same class.
Static method can call another non staic method of same class only after creating instance of the class.
Non static method can call another static method of same class simply by way of classname.methodname - No sure if this correct ?
My Question is about non static method call to another non staic method of same class. In class declaration, when we declare all methods, can we call another non static method of same class from a non static class ?
Please explain with example. Thank you.
Your #3, is correct, you can call static methods from non-static methods by using classname.methodname.
And your question seems to be asking if you can call non-static methods in a class from other non-static methods, which is also possible (and also the most commonly seen).
For example:
public class Foo {
public Foo() {
firstMethod();
Foo.staticMethod(); //this is valid
staticMethod(); //this is also valid, you don't need to declare the class name because it's already in this class. If you were calling "staticMethod" from another class, you would have to prefix it with this class name, Foo
}
public void firstMethod() {
System.out.println("This is a non-static method being called from the constructor.");
secondMethod();
}
public void secondMethod() {
System.out.println("This is another non-static method being called from a non-static method");
}
public static void staticMethod() {
System.out.println("This is the static method, staticMethod");
}
}
A method is and should be in the first regard be semantically bound to either the class or the instance.
A List of something has a length or size, so you ask for the size of special List. You need an object of that class to call .size ().
A typical, well known example of a static method is Integer.parseInt ("123");. You don't have an Integer instance in that moment, but want to create one.
If, at all, we would bind that method to an instance, we would bind it to a String instance - that would make sense:
int a = "123".parseInt ();
That would have been a reasonable choice, but it would mean that similar methods for float, double, long, short, Boolean and maybe every class which has a symmetric "toString" method would have to be put into String. That would have meant a zillion of extensions to the String class.
Instead String is final, so a reasonable place to put such a method is the target class, like Integer, Float and so on.
not sure that I understand the question correctly, but non-static methods are the standard way to design classes in OO. Maybe this sample will help spark the discussion:
public class MySampleClass{
private void methodA(){
System.out.println('a called');
}
public void methodB(){
this.methodA();
staticMethod(this);
}
private static void staticMethod( MySampleClass inst ){
inst.methodA();
}
}
You can call non-static method from non-static method using explicitly reference to object on which you want to call that method someObject.method, or without specifying that object someMethod() (in this case it will be invoked on same object that you are invoking current non-static method).
Maybe this will show it better
class Demo {
private String name;
public Demo(String n) {
name = n;
}
public String getName() {// non static method
return name;
}
public void test(Demo d) {// non-static method
System.out.println("this object name is: "+getName());// invoking method on this object
System.out.println("some other object name is: "+d.getName());// invoking method on some other object
}
//test
public static void main(String[] args) {
Demo d=new Demo("A");
Demo d2=new Demo("B");
d.test(d2);
}
}
output:
this object name is: A
some other object name is: B
public class TestClass{
public static void testStatic(){
System.out.println("test1");
}
public void testNonStatic(){
System.out.println("test2");
}
public void test1(){
// both is valid
testStatic();
TestClass.testStatic();
// this is valid, cause it can call the method of the same instance of that class
testNonStatic();
this.testNonStatic();
// this is not valid, cause without a concrete instance of a class you cannot call
// non static methods
TestClass.testNonStatic();
}
public static void test2(){
// again these are both correct
testStatic();
TestClass.testStatic();
// this doesn't work, cause you cannot call non static methods out of static methods
testNonStatic();
this.testNonStatic();
// this instead does work cause you have a concrete instance of the object
TestClass myTestClass = new TestClass();
myTestClass.testNonStatic();
// this still doesn't work
TestClass.testNonStatic();
}
}
Related
I was facing an error before, but when I made an object in this class the and called for the method, it worked flawlessly. Any explanation? Do I always have to make an object to call for methods outside of the main method (but in the same class)?
here:
public class A{
public static void main(String[] args){
A myObj= new A();
System.out.println(myObj.lets(2));
}
public int lets(int x){
return x;
}
}
You need to understand static. It associates a method or field to the class itself (instead of a particular instance of a class). When the program starts executing the JVM doesn't instantiate an instance of A before calling main (because main is static and because there are no particular instances of A to use); this makes it a global and an entry point. To invoke lets you would need an A (as you found), or to make it static (and you could also limit its' visibility) in turn
private static int lets(int x) {
return x;
}
And then
System.out.println(lets(2));
is sufficient. We could also make it generic like
private static <T> T lets(T x) {
return x;
}
and then invoke it with any type (although the type must still override toString() for the result to be particularly useful when used with System.out.println).
There are a importance concept to consider an is static concept. In your example you have to create an instance of your class because the main method is static and it only "operate" with other statics methods or variable. Remember that when you instantiate a class you are creating a copy of that class an storing that copy in the instance variable, so as the copy (That was create inside of a static method in your case) is also static so it can access the method which is not static in that context.
In order to not create an instance and access to your method you need to make your lets method static(due to the explanation abode)
public static int lets(int x){
return x;
}
And in your main you don't need to instantiate the class to access to this method.
public static void main(String[] args){
System.out.println(lets(2));
}
Check this guide about static in java: https://www.baeldung.com/java-static
Hope this help!
So I am a bit new to Java. I just got introduced to interfaces and i have to create a method that returns an instance of the interface Chassis
Below is the code:
public interface Chassis {
public String Chassis = "Chassis";
public static void main(String[] args) {
public String getChassisType() {
return Chassis;
}
The problem is, I keep getting error that abstract methods cannot have a body (as indicated by the blockquote) yet i had not declared my method as abstract.
What seems to be the problem?
You have two problems, You can't put a method inside another method, and you can't define a method like this in an interface in Java. In Java 8 you can do this
public interface Chassis {
String Chassis = "Chassis";
default String getChassisType(){
return Chassis;
}
}
I wouldn't define your public static void main inside an interface. While it is allowed now, most developers would find this confusing. See #Jürgen's answer, as this what most experienced developers would say I believe.
I would create another class like
public class Main {
public static void main(String... args) {
// an anonymous subclass so you have something to create/call.
System.out.println(new Chassis(){}.getChassisType());
}
}
An interface is a kind of abstract. It cannot be instantiated, It can have only declaration of methods and attributes not definition. You can only implement it in a class, if you do so in a class you must define all the methods which are declared in the interface. A main method need to be defined in order to execute the program. So it should not be placed inside an interface. change your code like this below
public interface chassis
{
String Chassis;
public String chassis();
}
public class example implements chassis
{
public String chassis()
{
Chassis="chassis";
return Chassis;
}
public static void main(String[] args)
{
System.out.println(new example().getChassisType());
}
}
This code would not work at all. A main method is only valid for classes, not for interfaces.
EDIT: as stated below the answer is not correct. But having a method inside a method still does not work. See the other answers.
Seems like a very basic query but I was pondering how the static method main() below is able to execute a non static method(the constructor obviously) from it using the new keyword. Though I understand that new brings onto the table a few other things as well but how should I convince myself that this isn't an exception to the rule that static and non static methods can't using non static and static context respectively?
Below is the sample code:
public class ConstructorTest {
ConstructorTest(String str)
{
System.out.println("Constructor Printing "+str);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ConstructorTest cnst=new ConstructorTest("here");
}
}
The above code actually prints --> Constructor Printing here
or in other words executing the body of a Non static method from a Static method?
Any plausible explanations are welcome.
The Java Tutorial states that
[...] Constructors are not members.
Therefore, there is no problem in calling them, since they are not bound to instances of your class. This would not make sense - hence, you cannot do the following:
Thing thing = new Thing();
Thing anotherThing = thing.Thing();
A constructor is not a method, so you cannot apply "method logic" to them.
In case you want to know more, the whole instantiation process is very well documented in the JLS. See 12.5. Creation of New Class Instances.
Actually constructor is compiled into the static method, this is how JVM internally creates instances of classes.
You are executing non-static code, but you are not doing it in a static context.
for instance:
public class C1{
private int x;
public String do(){ System.out.println("x = " + x);}
public static void main(String[] args){
do();
}
}
This can not work, since do is an instance method, which might run code that is specific to the instance. So, how would the VM know which instance to use, or what value x should have?
Now, to first use a constructor, which is possible from any context:
public class C1{
private int x;
public String do(){ System.out.println("x = " + x);}
public static void main(String[] args){
C1 t = new C1();
t.do();
}
}
Here, even though you are calling the method from within a static method, you are using it through an instance, so not in a static context.
ConstructorTest is not a method.
its an constructor,and you can use the constructor for initialize class property.
you can also initialize the static variable from the constructor like that :-
public class XYZ
{
static int i=0;
public XYZ() {
i=1;//not an compile time error
}
public static void doSome(){}
public static void main(String[] args) {
}
}
On a formal language level you should read the line
ConstructorTest cnst = new ConstructorTest("here")
as a class instance creation expression. As a matter of fact, this is not a call to a constructor or any other method.
The instance creation does many steps, like allocating memory for the new object, initializing the fields, calling constructors and initializer blocks. See JLS §12.5 for a detailed step-by-step description. Thus being said, the constructor invocation is only a part of the instance creation.
Additionally, you might see constructors as being static parts of the class. In fact, constructor declaration are not members (see JLS §8.8) and thus they are not overridable (as static methods also). Beware: This is only half true. When being inside the constructor you already have the instance created, and you are able to call other instance methods and/or access instance fields.
When studying the java programming language, I meet the following statement
I am confusing about the statement marked with yellow. Especially, what does instance method mean here? If there is an example to explain this point, then it would be much appreciated.
If I have a method:
public static void print(String line) {
System.out.println(line);
}
... and then remove the static keyword ...
public void print(String line) {
System.out.println(line);
}
... it is now an instance method, can no longer be invoked from the class, and must instead be invoked from an instance (hence the name).
e.g.,
MyClass.print(line);
vs.
new MyClass().print(line);
That's really it.
You can call static methods without needing to intantiate an object:
TestObject.staticMethodCall();
For non-static methods you need to create an instance to call a method on:
new TestObject().nonStaticMethodCall();
Consider following sequence.
Define Class X with static void foo() a static method
Define Class Y which calls X.foo() in its main method
Compile the two classes and (somehow) run it
Change X.foo() to be a instance method by removing the static qualifier
Compile only X, not Y
Run the Y class again and observe the error.
On the other hand, if you had changed the body of X.foo in certain ways without changing its static-ness then there would have been no error. For more, look up "binary compatibility"
First of all, you should understand the difference between the class method and the instance method. An example is shown below.
public Class Example{
public static void main(String[] args) {
Example.method1();//or you can use method1() directly here
Example A = new Example();
A.method2();
}
public static void method1(){
}
public void method2(){
}
}
method1 is the class method which you can take it as the method of the class. You can invoke it without initiating a object by new method. So you can invoke it in such way: Example.method1()
method2 is the instance method which requires you to invoke it by initiating the instance of an object, i.e. Example A = new Example(); A.method2();
Additional:
The error is due to the removal of the static modifier of an class method like method1. Then method1 becomes an instance method like method2 which you have to initiate an instance to call.
When a class extends another, it inherits all methods and variables of the superclass. Both methods and variables can be used differently in the subclass, if you define it differently in the subclass with the same signature.
Now Oracle distincts between overwriting and hiding (http://docs.oracle.com/javase/tutorial/java/IandI/override.html).
It says that an instance method overwrites its superclass's method, while a class method hides it.
"The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass."
Lets assume I have 2 classes Yes and Maybe. Yes extends Maybe.
Maybe has String a.
class Maybe {
String a;
public static void printOut() {
System.out.println("Maybe");
}
public void printAndSet() {
a = "Maybe";
System.out.println(a);
}
}
class Yes extends Maybe {
public static void printOut() {
System.out.println("Yes");
}
pubilc void printAndSet() {
a = "Yes";
}
}
class Print{
public static void mail(String[] args) {
Maybe m = new Maybe();
Yes y = new Yes();
Maybe.printOut();
Yes.printOut();
m.printAndSet();
y.printAndSet();
}
And I say: It will print out
maybe
yes
maybe
yes
But after I read the Oracle article I thought it would have to print out:
yes
yes
maybe
yes
Because the instance method overwrites its superclass method.
I'm quite sure I am right with the output, but I'm sure aswell, that Oracle knows
better so I'm thinking I just didn't understand the article.
It can't be true that when I call an instance method from an object of a superclass, that it uses the overwritten method.
So I do not understand why to distinguish overwriting and hiding!
Can someone help out?
Edit; Inserted code instead of describing the classes!
Static methods can't be overridden at all. They're not called polymorphically, since they don't act on an instance of the class, but on the class itself.
If you call Maybe.printOut(), it will call the static printOut() method defined in Maybe. The fact that there is also a method printOut() defined in Yes is irrelevant: those two methods have nothing in common, except their name.
Note that you could confirm or infirm your doubts by simply writing a program and executing it.
The problem with hiding methods only occurs when you start calling static methods on an instance of an object. This is very bad practice, and should never be done. If you don't respect this rule, and have the following:
Maybe m = new Maybe();
Maybe y = new Yes();
m.printOut(); // DON'T DO THAT: it should be Maybe.printOut();
y.printOut(); // DON'T DO THAT: it should be Maybe.printOut() or Yes.printOut();
the result will be maybe maybe, because in the case of static methods, what counts is not the concrete type of the objects (Maybe and Yes), but their declared type (Maybe and Maybe).
public class Parent {
public String test(){
return "p";
}
public static String testStatic(){
return "sp";
}
}
public class Child extends Parent {
public String test(){
return "c";
}
public static String testStatic(){
return "sc";
}
}
public class Demo{
public static void main(String[] args) {
Parent p =new Parent();
Child c = new Child();
Parent pc = new Child();
System.out.println(p.test());
System.out.println(c.test());
System.out.println(pc.test());
//Although this is not the correct way of calling static methods
System.out.println(p.testStatic());
System.out.println(c.testStatic());
System.out.println(pc.testStatic());
}
}
OUTPUT will be: - (static method vs instance method)
p
c
c
sp
sc
sp
Take the following example, based on your example:
public class SO11720216 {
static class Maybe {
public static void hidden() { System.out.println("static maybe"); }
public void overwritten() { System.out.println("instance maybe"); }
public void inherited() { hidden(); }
public void called() { overwritten(); inherited(); }
}
static class Yes extends Maybe {
public static void hidden() { System.out.println("static yes"); }
public void overwritten() { System.out.println("instance yes"); }
}
public static void main(String[] args) {
Maybe m = new Maybe();
Yes y = new Yes();
m.called(); /* prints:
instance maybe
static maybe
*/
y.called(); /* prints:
instance yes
static maybe
*/
Yes.hidden(); /* prints: static yes */
y.hidden(); /* bad style! prints: static yes */
}
}
The call to overwritten will be overwritten by each derived class. So every method will use the implementation belonging to the current object. On the other hand, the call to hidden will always use the implementation of the defining class. Hence Maybe.called will always call Maybe.hidden, and never Yes.hidden. To call Yes.hidden, you'll have to do so from within a method in Yes, or using a qualified name.
To phrase this differently:
To overwrite a method means that whenever the method is called on an object of the derived class, the new implementation will be called.
To hide a method means that an unqualified call to that name (like the hidden() call in the inherited() method of my above example) in the scope of this class (i.e. in the body of any of its methods, or when qualified with the name of this class) will now call a completely different function, requiring a qualification to access the static method of the same name from the parent class.
Perhaps your confusion comes from the fact that you assumed overwriting to affect all calls to the method, even for objects of the base class.