Java private method override - java

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!)

Related

Does object in java created on heap before Constructor is invoked?

When overridden methods are called from the Constructor of the base class then also as per the run time polymorphism concept the method defined in the sub class gets invoked. I wonder as how this is taken care of in the JVM, when control is in the base class constructor the constructor of the sub class is yet to be called and hence Object is not yet completely constructed.
I understand the ill effects of calling overriden methods from base class constructor but just wish to understand as how this is made possible.
I feel object in the heap is created before constructor is invoked and as constructor is invoked the properties are initialized. Please provide your valuable inputs for the above.
Below is the code demonstrating the same.
Base.java
public class Base {
public Base() {
System.out.println("Base constructor is executing...");
someMethod();
}
public void someMethod() {
System.out.println("someMethod defined in Base class executing...");
}
}
Sub.java
public class Sub extends Base{
public Sub() {
System.out.println("Sub constructor is executing...");
}
#Override
public void someMethod() {
System.out.println("someMethod defined in Sub class executing...");
}
}
Client.java
public class Client {
public static void main(String[] args) {
Sub obj = new Sub();
}
}
Output on console is
Base constructor is executing...
someMethod defined in Sub class executing...
Sub constructor is executing...
Does object in java created before Constructor is invoked ?
Yes, otherwise you would not have an object to initialise.
At the byte code level, the object is created first, and then the constructor is called, passing in the object to initialise. The internal name for a constructor is <init> and it's return type is always void meaning it doesn't return the object, only initialise it.
Note: Unsafe.allocateInstance will create an object without calling a constructor and is useful for de-serialization.

What is the use of main method in abstract class?

I know that we can write main method in abstract class, but what we can achieve from it ?
public abstract class Sample
{
public static void main(String args[])
{
System.out.println("Abstract Class main method : ");
}
}
We can not create the object of abstract class ,so what is the use of main method in abstract class ?
Abstract just means you can't instantiate the class directly.
Loading a class is not the same as creating an instance of the class. And there's no need to create an instance of the class to call main(), because it's static. So there's no problem.
Abstract just means you can't instantiate the class directly. You can have constructors if you want - they might be needed for subclasses to initiate the object state. You can have static methods, including main() and they don't need an object so calling them is fine.
So you only got error when you try to create the object, which is when you run into the abstract limitation.
You can extend the abstract class and then the child class has a main method without specifying one there.
public abstract class Abstrc
{
Abstrc(){} // constructor
public abstract void run(); // abstract method
public static int mul(){return 3*2;} // static method
public static void main(String[] args)
{ // Static method that can be accessed without instantiation
System.out.println("Your abstract no is : " + Abstrc.mul());
}
}
Your abstract no is : 6
As Zeeshan already said, since the main method is static, it does not require an instance to be called. As to what can be achieved by placing the main method in an abstract class, well nothing more or less than placing it in any other class.
Typically, the main method is either placed in a class of its own or in a class that is central to the application. If that class happens to be abstract, so be it.

Trying to call a method in a method from another class

public void toonBoten()
{
for(Boot tweedeboot: boten)
{
Boot.toonBoot();
}
}
I'm trying to call the method toonBoot from the class Boot. This should be done for every tweedeboot of the type Boot (same as the class) from the ArrayList boten. toonBoot prints a few lines of information (basically it's a number of coordinates).
For some reason, I always receive the error "non-static method toonBoot() cannot be referenced from a static context".
What am I doing wrong?
Thanks!
You have to call method on instance.
public void toonBoten()
{
for(Boot tweedeboot: boten)
{
tweedeboot.toonBoot();
}
}
Where
Boot.toonBoot(); //means toonBoot() is a static method in Boot class
See:
Understanding Instance and Class Members
What you are doing
By calling the method from the Class name, you're telling the compiler that this method is a static method. That is, calling Boot.hello() that the method signature for hello() is something like:
public static void hello() {}
What you should do
Call from the object reference, or in this case tweedeboot. This tells the compiler that the method is either a static method or an instance method, and it will check the instance as well as the class.

Java jframe use of functions of main

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.

Calling Non-Static Method In Static Method In Java [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 5 years ago.
I'm getting an error when I try to call a non-static method in a static class.
Cannot make a static reference to the non-static method methodName() from the type playback
I can't make the method static as this gives me an error too.
This static method cannot hide the instance method from xInterface
Is there any way to get round calling an non-static method in another static method? (The two methods are in seperate packages and seperate classes).
The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.
You could create an instance of the class you want to call the method on, e.g.
new Foo().nonStaticMethod();
Firstly create a class Instance and call the non-static method using that instance.
e.g,
class demo {
public static void main(String args[]) {
demo d = new demo();
d.add(10,20); // to call the non-static method
}
public void add(int x ,int y) {
int a = x;
int b = y;
int c = a + b;
System.out.println("addition" + c);
}
}
public class StaticMethod{
public static void main(String []args)throws Exception{
methodOne();
}
public int methodOne(){
System.out.println("we are in first methodOne");
return 1;
}
}
the above code not executed because static method must have that class reference.
public class StaticMethod{
public static void main(String []args)throws Exception{
StaticMethod sm=new StaticMethod();
sm.methodOne();
}
public int methodOne(){
System.out.println("we are in first methodOne");
return 1;
}
}
This will be definitely get executed. Because here we are creating reference which nothing but "sm" by using that reference of that class which is nothing
but (StaticMethod=new Static method()) we are calling method one (sm.methodOne()).
I hope this will be helpful.
You need an instance of the class containing the non static method.
Is like when you try to invoke the non-static method startsWith of class String without an instance:
String.startsWith("Hello");
What you need is to have an instance and then invoke the non-static method:
String greeting = new String("Hello World");
greeting.startsWith("Hello"); // returns true
So you need to create and instance to invoke it.
It sounds like the method really should be static (i.e. it doesn't access any data members and it doesn't need an instance to be invoked on). Since you used the term "static class", I understand that the whole class is probably dedicated to utility-like methods that could be static.
However, Java doesn't allow the implementation of an interface-defined method to be static. So when you (naturally) try to make the method static, you get the "cannot-hide-the-instance-method" error. (The Java Language Specification mentions this in section 9.4: "Note that a method declared in an interface must not be declared static, or a compile-time error occurs, because static methods cannot be abstract.")
So as long as the method is present in xInterface, and your class implements xInterface, you won't be able to make the method static.
If you can't change the interface (or don't want to), there are several things you can do:
Make the class a singleton: make the constructor private, and have a static data member in the class to hold the only existing instance. This way you'll be invoking the method on an instance, but at least you won't be creating new instances each time you need to call the method.
Implement 2 methods in your class: an instance method (as defined in xInterface), and a static method. The instance method will consist of a single line that delegates to the static method.
The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method.
class A
{
void method()
{
}
}
class Demo
{
static void method2()
{
A a=new A();
a.method();
}
/*
void method3()
{
A a=new A();
a.method();
}
*/
public static void main(String args[])
{
A a=new A();
/*an instance of the class is created to access non-static method from a static method */
a.method();
method2();
/*method3();it will show error non-static method can not be accessed from a static method*/
}
}
There are two ways:
Call the non-static method from an instance within the static method. See fabien's answer for an oneliner sample... although I would strongly recommend against it. With his example he creates an instance of the class and only uses it for one method, only to have it dispose of it later. I don't recommend it because it treats an instance like a static function.
Change the static method to a non-static.
You can't get around this restriction directly, no. But there may be some reasonable things you can do in your particular case.
For example, you could just "new up" an instance of your class in the static method, then call the non-static method.
But you might get even better suggestions if you post your class(es) -- or a slimmed-down version of them.
The easiest way to use a non-static method/field within a a static method or vice versa is...
(To work this there must be at least one instance of this class)
This type of situation is very common in android app development eg:- An Activity has at-least one instance.
public class ParentClass{
private static ParentClass mParentInstance = null;
ParentClass(){
mParentInstance = ParentClass.this;
}
void instanceMethod1(){
}
static void staticMethod1(){
mParentInstance.instanceMethod1();
}
public static class InnerClass{
void innerClassMethod1(){
mParentInstance.staticMethod1();
mParentInstance.instanceMethod1();
}
}
}
Note:- This cannot be used as a builder method like this one.....
String.valueOf(100);
I use an interface and create an anonymous instance of it like so:
AppEntryPoint.java
public interface AppEntryPoint
{
public void entryMethod();
}
Main.java
public class Main
{
public static AppEntryPoint entryPoint;
public static void main(String[] args)
{
entryPoint = new AppEntryPoint()
{
//You now have an environment to run your app from
#Override
public void entryMethod()
{
//Do something...
System.out.println("Hello World!");
}
}
entryPoint.entryMethod();
}
public static AppEntryPoint getApplicationEntryPoint()
{
return entryPoint;
}
}
Not as elegant as creating an instance of that class and calling its own method, but accomplishes the same thing, essentially. Just another way to do it.
It is not possible to call non-static method within static method. The logic behind it is we do not create an object to instantiate static method, but we must create an object to instantiate non-static method. So non-static method will not get object for its instantiation inside static method, thus making it incapable for being instantiated.
Constructor is a special method which in theory is the "only" non-static method called by any static method. else its not allowed.
You can call a non static method within a static one using:
Classname.class.method()

Categories

Resources