static
public class Hello {
public static int age;
public static String DoSomething(String message)
{
return(message);
}
public String DoSomethingElse(String message)
{
return(message);
}
}
public class StaticHello {
public static void main(String[] args) {
// TODO Auto-generated method stub
Hello hello0 = new Hello();
System.out.println(Hello.DoSomething("HI")); //static
System.out.println(hello0.DoSomethingElse("Bye")); //non-static
Hello.age = 10;//static
System.out.println(Hello.age);
}
}
Difference:
- Call
static: (ClassName. xx)
non-static: (InstanceName. xx) - Definition
static: belong to the type itself
non-static: belong to the instance of that type
Since static variables belong to a class, they can be accessed directly using class name and don’t need any object reference.
static variables can only be declared at the class level.
static fields can be accessed without object initialization.
Although we can access static fields using an object reference , we should refrain from using it as in this case it becomes difficult to figure whether it’s an instance variable or a class variable; instead, we should always refer to static variables using class name.
(from: A Guide to the Static Keyword in Java)
Example:
public class Eg {
public static void main(String[] args) {
EgStudent mark = new EgStudent();
mark.setAge(19);
System.out.println(mark.getAge());
EgStudent tom = new EgStudent();
tom.setName("Tom");
System.out.println(tom.getName());
System.out.println(EgStudent.NoOfStudent);
}
}
public class EgStudent {
String name;
int age;
static int NoOfStudent = 0;
EgStudent () {
NoOfStudent++;
} // once EgStudent is called, number of student plus one
public static int getNoOfStudent() {
return NoOfStudent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
final
/*final:
* A final class cannot be subclassed.
* A final method cannot be overridden by a subclass.
* A final variable can only be initialized once.
*/
public class Final {
public final int number;
Final () {
number = 10;
}
}
abstract
public class TestAbstract {
public static void main(String[] args) {
Baank abc = new Bank_ABC();
/* "Baank abc = new Baank()" cannot be used anymore,
* because Baank class is abstracted now,
* it cannot be instantiated.
*/
System.out.println(abc.getIR());
}
}
abstract public class Baank {
abstract int getIR();
/* abstract class -->abstract method
* write implementations in the subclass
*/
}
//concrete
class Bank_ABC extends Baank {
int getIR() {
return 6;
}
}