What is method hiding in Java?

When you declare two static methods with same name and signature in both superclass and subclass then they hide each other i.e. a call to the method in the subclass will call the static method declared in that class and a call to the same method is superclass is resolved to the static method declared in the super class.

Can we overload and overload a static method in Java?

Yes, you can overload a static method in Java. You can declare as many static methods of the same name as you wish provided all of them have different method signatures.

Can you access a non-static variable in the static context?

Another tricky Java question from Java fundamentals. No, you can not access a non-static variable from the static context in Java. If you try, it will give compile time error. This is actually a common problem beginner in Java face when they try to access instance variable inside the main method. Because main is static in Java, and instance variables are non-static, you can not access instance variable inside main.

对于一个属性被static所修饰,不管MyStatic生成了多少实例,那么这多个实例共同使用这个属性。


public class StaticTest {

    public static void main(String[] args) {
        MyStatic mystatic = new MyStatic();
        MyStatic mystatic2 = new MyStatic();
        mystatic.c = 10;
        System.out.println(mystatic2.c);
    }
}

class MyStatic {

    static int c;
}

static 修饰方法:static 修饰的方法叫做静态方法。对于静态方法来说,可以使用

类名.方法名的方式来访问。

public class StaticTest2 {

    public static void main(String[] args) {
        //MyStatic2 test = new MyStatic2();  
        //test.output();  
        MyStatic2.output();
    }
}

class MyStatic2 {

    public static void output() {
        System.out.println("output");
    }
}
  1. 静态方法只能继承,不能重写(Override).这个时候是隐藏了父类的静态方法,没有发生重写。同时静态方法不能覆盖非静态的方法,非静态的方法不能覆盖静态方法

results matching ""

    No results matching ""