public String publicVariable = "This is a public variable"; protected String protectedVariable = "This is a protected variable"; private String privateVariable = "This is a private variable"; String defaultVariable = "This is a default variable";
public void publicMethod() { System.out.println("This is a public method"); }
protected void protectedMethod() { System.out.println("This is a protected method"); }
private void privateMethod() { System.out.println("This is a private method"); }
void defaultMethod() { System.out.println("This is a default method"); }
public static void main(String[] args) { AccessModifierExample example = new AccessModifierExample();
System.out.println(example.publicVariable); // Output: This is a public variable System.out.println(example.protectedVariable); // Output: This is a protected variable System.out.println(example.privateVariable); // Compilation error System.out.println(example.defaultVariable); // Output: This is a default variable
example.publicMethod(); // Output: This is a public method example.protectedMethod(); // Output: This is a protected method example.privateMethod(); // Compilation error example.defaultMethod(); // Output: This is a default method } }
public class FinalExample { public static void main(String[] args) { final int a = 10; //a = 20; // 编译错误,因为a被final修饰,不能再次赋值 System.out.println("a的值是:" + a); } }
public abstract class Animal { private String name; public Animal(String name) { this.name = name; } public abstract void makeSound(); // 抽象方法 public void eat() { System.out.println(name + "正在吃东西"); } }
public class Dog extends Animal { public Dog(String name) { super(name); } public void makeSound() { System.out.println("汪汪汪"); } }
public class Cat extends Animal { public Cat(String name) { super(name); } public void makeSound() { System.out.println("喵喵喵"); } }
public class Main { public static void main(String[] args) { Animal dog = new Dog("旺财"); Animal cat = new Cat("小花"); dog.makeSound(); // 汪汪汪 cat.makeSound(); // 喵喵喵 } }
public class Counter { private static int count = 0; // 静态变量 public Counter() { count++; } public static int getCount() { // 静态方法 return count; } }
public class Main { public static void main(String[] args) { Counter c1 = new Counter(); Counter c2 = new Counter(); Counter c3 = new Counter(); System.out.println("对象数量:" + Counter.getCount()); // 对象数量:3 } }
public class NativeExample { public native void sayHello(); static { System.loadLibrary("NativeExample"); } public static void main(String[] args) { new NativeExample().sayHello(); } }