句法
访问修饰符:
公共
定义为公共的类、方法或变量可以被任何类或方法访问。
受保护
protec++ted 可以被同一个包的类访问,也可以被该类的子类访问,也可以在同一个类内访问。
(注意: 该关键字仅适用于嵌套类)
私人
定义为 private 的私有类、方法或变量只能在类内部访问。
默认
默认值只能在包内访问。默认情况下,所有类、方法和变量都具有默认范围。
package com.example; public class example { private int privatevar = 10; int defaultvar = 20; protected int protectedvar = 30; public int publicvar = 40; public static void main(string[] args) { example example = new example(); // accessing all variables within the same class system.out.println("private var: " + example.privatevar); system.out.println("default var: " + example.defaultvar); system.out.println("protected var: " + example.protectedvar); system.out.println("public var: " + example.publicvar); } } //another file package com.example; public class example1 { public static void main(string[] args) { example example = new example(); // private variable is inaccessible system.out.println("default var: " + example.defaultvar); system.out.println("protected var: " + example.protectedvar); system.out.println("public var: " + example.publicvar); } } // file: different.java package com.example.subpackage; import com.example.example; public class different extends example { public static void main(string[] args) { example example = new example(); different subclassexample = new different(); // private variable is inaccessible // default variable is inaccessible // protected variable is inaccessible system.out.println("public var: " + example.publicvar); // accessing protected variable through inheritance system.out.println("protected var (through inheritance): " + subclassexample.protectedvar); } }
数据类型
public class main { // class to demonstrate structure equivalent static class person { string name; // default value is null int age; // default value is 0 float salary; // default value is 0.0f } // enumeration to demonstrate enum equivalent enum color { red, green, blue } public static void main(string[] args) { // basic data types int a = 10; // default value is 0 float b = 5.5f; // default value is 0.0f char c = 'a'; // default value is 'u0000' double d = 2.3; // default value is 0.0d long e = 123456789l; // default value is 0l short f = 32000; // default value is 0 byte g = 100; // default value is 0 // array int[] arr = {1, 2, 3, 4, 5}; // structure equivalent person person1 = new person(); person1.age = 30; person1.salary = 55000.50f; // enumeration color mycolor = color.red; } }
超载
当同一个类中多个方法具有相同名称但参数不同时,就会发生方法重载。这是在编译时解决的。
class mathoperations { // method to add two integers public int add(int a, int b) { return a + b; } // method to add three integers public int add(int a, int b, int c) { return a + b + c; } // method to add two double values public double add(double a, double b) { return a + b; } } public class main { public static void main(string[] args) { mathoperations math = new mathoperations(); system.out.println(math.add(2, 3)); system.out.println(math.add(1, 2, 3)); system.out.println(math.add(2.5, 3.5)); } }
压倒一切
当子类为其超类中已定义的方法提供特定实现时,就会发生方法重写。这在运行时解决了
class animal { public void makesound() { system.out.println("animal makes a sound"); } } class dog extends animal { @override public void makesound() { system.out.println("dog barks"); } } public class main { public static void main(string[] args) { animal myanimal = new animal(); myanimal.makesound(); // calls method in animal class dog mydog = new dog(); mydog.makesound(); // calls overridden method in dog class } }
大批
数组和对象始终通过引用传递,而不是复制。原始数据类型按值传递。
public class main { public static void main(string[] args) { // integer array int[] intarray = new int[5]; // default values: 0 int[] intarray2 = {1, 2, 3, 4, 5}; // initialized with specific values // float array float[] floatarray = new float[5]; // default values: 0.0f float[] floatarray2 = {1.1f, 2.2f, 3.3f, 4.4f, 5.5f}; // initialized with specific values } }
默认关键字
默认方法是在接口中使用 default 关键字定义的方法。这允许接口提供方法实现,而不影响实现该接口的类。
interface animal { void makesound(); // abstract method // default method default void sleep() { system.out.println("sleeping..."); } } class dog implements animal { public void makesound() { system.out.println("bark"); } } public class main { public static void main(string[] args) { animal dog = new dog(); dog.makesound(); // output: bark dog.sleep(); // output: sleeping... } }
静态关键字
它表示成员(变量、方法或嵌套类)属于类本身,而不是属于类的实例。
(注意: 我们不能在非静态方法中声明静态变量)
public class staticexample { // static variable static int staticvariable = 10; // instance variable int instancevariable = 20; // static method static void staticmethod() { // can access static variable system.out.println(staticvariable); // cannot access instance variable directly // system.out.println(instancevariable); } // instance method void instancemethod() { // can access static variable system.out.println(staticvariable); // can access instance variable system.out.println(instancevariable); } // static nested class static class staticnestedclass { void display() { system.out.println("static nested class method called."); // can access static members of the outer class system.out.println("static variable from nested class: " + staticvariable); } } public static void main(string[] args) { // call static method staticexample.staticmethod(); // create an instance of the class staticexample example = new staticexample(); // call instance method example.instancemethod(); // create an instance of the static nested class staticnestedclass nestedclass = new staticnestedclass(); nestedclass.display(); } }
初始化
(注意: 只有实例变量和静态变量会被初始化为默认值)
import java.util.scanner; public class inputexample { public static void main(string[] args) { int num; int num1=0; system.out.println(num); //throws error system.out.println(num1); // prints 0 } }
显示类的方法及其参数
import java.lang.reflect.method; import java.lang.reflect.parameter; import java.util.linkedlist; public class main { public static void main(string[] args) { class> clazz = linkedlist.class; // get all methods of the class method[] methods = clazz.getdeclaredmethods(); // print the names and parameters of all methods for (method method : methods) { system.out.print("method name: " + method.getname()); system.out.print(", parameters: "); parameter[] parameters = method.getparameters(); for (parameter parameter : parameters) { system.out.print(parameter.gettype().getname() + " " + parameter.getname() + ", "); } system.out.println(); } } }
基本输入/输出
import java.util.scanner; public class inputexample { public static void main(string[] args) { scanner scan = new scanner(system.in); // reading integer input system.out.print("enter an integer: "); int intvalue = scan.nextint(); system.out.println("integer entered: " + intvalue); // reading double input system.out.print("enter a double: "); double doublevalue = scan.nextdouble(); system.out.println("double entered: " + doublevalue); // reading string input (including spaces) system.out.print("enter a string: "); scan.nextline(); // consume the newline character string stringvalue = scan.nextline(); system.out.println("string entered: " + stringvalue); // reading character input system.out.print("enter a character: "); char charvalue = scan.next().charat(0); system.out.println("character entered: " + charvalue); // reading boolean input system.out.print("enter a boolean (true/false): "); boolean booleanvalue = scan.nextboolean(); system.out.println("boolean entered: " + booleanvalue); // reading input until there is no more input available system.out.println("enter multiple lines of input (ctrl+d / ctrl+z to exit):"); scan.nextline(); // consume the newline character while (scan.hasnext()) { string line = scan.nextline(); system.out.println("input: " + line); } scan.close(); } }
for循环
public class main { public static void main(string[] args) { for (int i = 0; i <h2> while 循环 </h2> <pre class="brush:php;toolbar:false">public class main { public static void main(string[] args) { int i = 0; while (i <h2> 功能 </h2> <pre class="brush:php;toolbar:false">public class main { public static int add(int a, int b) { return a + b; } public static void main(string[] args) { int result = add(5, 3); system.out.println("sum: " + result); } }
类和对象
public class rectangle { private int width, height; public rectangle(int w, int h) { this.width = w; this.height = h; } public int area() { return width * height; } public static void main(string[] args) { rectangle rect = new rectangle(5, 3); system.out.println("area: " + rect.area()); } }
遗产
public class shape { public void draw() { system.out.println("drawing a shape"); } } public class circle extends shape { @override public void draw() { system.out.println("drawing a circle"); } public static void main(string[] args) { shape shape = new circle(); shape.draw(); } }
最终关键词
它是通过添加final关键字
创建的1) 最终变量
该变量一旦初始化就无法更改
public class finalvariableexample { public static void main(string[] args) { final int x = 10; // x = 20; // this will cause a compilation error system.out.println(x);// 10 } }
2)最终方法
这些方法不能被覆盖
class parent { final void show() { system.out.println("this is a final method."); } } class child extends parent { // void show() { // this will cause a compilation error // system.out.println("trying to override."); // } } public class finalmethodexample { public static void main(string[] args) { child c = new child(); c.show(); // output: this is a final method. } }
超级关键词
java中的super关键字用于引用当前对象的直接父类。它提供了一种从子类中访问父类的成员(方法和变量)的方法。
class parent { int x = 10; void display() { system.out.println("parent's display method"); } parent() { system.out.println("parent's constructor"); } } class child extends parent { int x = 20; void display() { super.display(); // calls the display method of parent class system.out.println("child's display method"); } child() { super(); // calls the constructor of parent class system.out.println("child's constructor"); } } public class test { public static void main(string[] args) { child obj = new child(); system.out.println("value of x in child: " + obj.x); obj.display(); } }
抽象的
java中的abstract关键字用于定义抽象类和抽象方法。抽象类不能直接实例化,只能进行子类化。抽象方法没有主体,必须由子类实现。
它包含抽象方法和具体方法
abstract class animal { // abstract method (does not have a body) abstract void makesound(); // regular method void eat() { system.out.println("this animal is eating."); } } class dog extends animal { // the body of the abstract method is provided here void makesound() { system.out.println("woof"); } } public class main { public static void main(string[] args) { dog mydog = new dog(); mydog.makesound(); // output: woof mydog.eat(); // output: this animal is eating. } }
当一个接口想要继承另一个接口的方法时,可以使用extends关键字。
抽象类可以实现接口。这意味着抽象类使用implements关键字提供了接口的部分实现。
一个抽象类可以使用 extends 关键字扩展另一个抽象类
立即学习“Java免费学习笔记(深入)”;
界面
是类似于类的引用类型,只包含常量、默认方法、静态方法和方法签名
(注意: 接口中只存在默认方法的定义)
(注:接口内声明的常量为public、static和final)
interface animal { void makesound(); // abstract method } class dog implements animal { public void makesound() { system.out.println("bark"); } } class cat implements animal { public void makesound() { system.out.println("meow"); } } public class main { public static void main(string[] args) { animal dog = new dog(); animal cat = new cat(); dog.makesound(); // output: bark cat.makesound(); // output: meow } }
克服钻石问题(多重继承):
interface a { void display(); } interface b extends a { default void display() { system.out.println("display from b"); } } interface c extends a { default void display() { system.out.println("display from c"); } } class d implements b, c { @override public void display() { b.super.display(); c.super.display(); system.out.println("display from d"); } } public class main { public static void main(string[] args) { d d = new d(); d.display(); //output //display from b //display from c //display from d } }
列表
import java.util.linkedlist; import java.util.list; import java.util.arraylist; public class listexample { public static void main(string[] args) { // declare list as linkedlist list<character> list = new linkedlist(); // add elements list.add('a'); list.add('b'); list.add('c'); // change implementation to arraylist list = new arraylist(list); // add more elements list.add('d'); list.add('e'); // change implementation to vector list = new vector(list); // add more elements list.add('f'); list.add('g'); } } </character>
队列
java 中的 queue 接口是 java 集合框架的一部分,代表一个设计用于在处理之前保存元素的集合。它通常以 fifo(先进先出)方式对元素进行排序,但其他排序也是可能的,例如 deque 实现中的 lifo(后进先出)。
import java.util.linkedlist; import java.util.priorityqueue; import java.util.arraydeque; import java.util.queue; import java.util.deque; public class queueexample { public static void main(string[] args) { // using linkedlist as a queue queue<string> queue = new linkedlist(); queue.add("java"); queue.add("python"); queue.add("c++"); // reassigning to priorityqueue queue = new priorityqueue(); queue.add("java"); queue.add("python"); queue.add("c++"); // reassigning to arraydeque queue = new arraydeque(); queue.add("java"); queue.add("python"); queue.add("c++"); } } </string>
收藏
数组列表
1.动态调整大小
2.实现列表接口
import java.util.arraylist; public class main { public static void main(string[] args) { arraylist<integer> list = new arraylist(); list.add(1); list.add(2); list.add(3); for (int num : list) { system.out.print(num + " "); } system.out.println(); // inserting an element list.add(2, "ruby"); // accessing elements system.out.println("element at index 3: + list.get(3)); // removing an element list.remove(1); // size of the list system.out.println(list.size()); // check if list is empty system.out.println("is list empty? + list.isempty()); // check if list contains an element system.out.println(list.contains("java")); // index of an element system.out.println(list.indexof("javascript")); // last index of an element system.out.println(list.lastindexof("ruby")); // clear the list list.clear() } } </integer>
堆
import java.util.stack; public class stackexample { public static void main(string[] args) { // create a stack stack<string> stack = new stack(); // push elements onto the stack stack.push("java"); stack.push("python"); stack.push("c++"); // print the stack after pushes system.out.println("stack after pushes: " + stack); // get the size of the stack int size = stack.size(); system.out.println("size of stack: " + size); // peek at the top element without removing it string topelement = stack.peek(); system.out.println("top element (peek): " + topelement); // pop an element from the stack string poppedelement = stack.pop(); system.out.println("popped element: " + poppedelement); // print the stack after pop system.out.println("stack after pop: " + stack); // check if the stack is empty boolean isempty = stack.isempty(); system.out.println("is stack empty? " + isempty); // get the size of the stack after pop size = stack.size(); system.out.println("size of stack after pop: " + size); // search for an element int position = stack.search("java"); system.out.println("position of element 'java': " + position); } } </string>
链表
import java.util.linkedlist; public class linkedlistexample { public static void main(string[] args) { // create a new linkedlist linkedlist<string> linkedlist = new linkedlist(); // add elements to the linkedlist linkedlist.add("java"); linkedlist.add("python"); linkedlist.add("c++"); system.out.println("initial linkedlist: " + linkedlist); // add element at specific index linkedlist.add(1, "javascript"); system.out.println("after add(1, 'javascript'): " + linkedlist); // add element at the beginning linkedlist.addfirst("html"); system.out.println("after addfirst('html'): " + linkedlist); // add element at the end linkedlist.addlast("css"); system.out.println("after addlast('css'): " + linkedlist); // get elements system.out.println("first element: " + linkedlist.getfirst()); system.out.println("last element: " + linkedlist.getlast()); system.out.println("element at index 2: " + linkedlist.get(2)); // remove elements linkedlist.remove(); // removes the first element system.out.println("after remove(): " + linkedlist); linkedlist.remove(2); // removes the element at index 2 system.out.println("after remove(2): " + linkedlist); linkedlist.removefirst(); // removes the first element system.out.println("after removefirst(): " + linkedlist); linkedlist.removelast(); // removes the last element system.out.println("after removelast(): " + linkedlist); // check if the list contains a specific element system.out.println("contains 'python': " + linkedlist.contains("python")); // get the size of the list system.out.println("size of linkedlist: " + linkedlist.size()); // clear the list linkedlist.clear(); system.out.println("after clear(): " + linkedlist); // check if the list is empty system.out.println("is linkedlist empty? " + linkedlist.isempty()); } } </string>
哈希映射
import java.util.hashmap; public class main { public static void main(string[] args) { hashmap<string integer> map = new hashmap(); map.put("alice", 90); map.put("bob", 85); for (string key : map.keyset()) { system.out.println(key + ": " + map.get(key)); } } } </string>
细绳
public class stringexamples { public static void main(string[] args) { // creating an empty string string emptystring = new string(); system.out.println("empty string: "" + emptystring + """); // creating a string from another string string original = "hello, world!"; string copy = new string(original); system.out.println("copy of original: " + copy); // creating a string from a character array char[] chararray = {'j', 'a', 'v', 'a'}; string fromchararray = new string(chararray); system.out.println("string from char array: " + fromchararray); // length of the string int length = original.length(); system.out.println("length of original string: " + length); //check if two strings are equal string str1 = "java"; string str2 = "java"; system.out.println(str1.equals(str2)); // true // check if the string is empty boolean isempty = original.isempty(); system.out.println("is original string empty? " + isempty); // character at a specific index char charat2 = original.charat(2); system.out.println("character at index 2 in original string: " + charat2); // convert to uppercase string uppercasestr = original.touppercase(); system.out.println("uppercase: " + uppercasestr); // convert to lowercase string lowercasestr = original.tolowercase(); system.out.println("lowercase: " + lowercasestr); // character methods char ch1 = 'a'; char ch2 = 'a'; char ch3 = '1'; char ch4 = ' '; char ch5 = 'u2603'; // unicode character for snowman system.out.println("isdigit('1'): " + character.isdigit(ch3)); // true system.out.println("isletter('a'): " + character.isletter(ch1)); // true system.out.println("isletterordigit('a'): " + character.isletterordigit(ch2)); // true system.out.println("islowercase('a'): " + character.islowercase(ch2)); // true system.out.println("isuppercase('a'): " + character.isuppercase(ch1)); // true system.out.println("iswhitespace(' '): " + character.iswhitespace(ch4)); // true system.out.println("tolowercase('a'): " + character.tolowercase(ch1)); // 'a' system.out.println("touppercase('a'): " + character.touppercase(ch2)); // 'a' // reverse a string using stringbuilder string reversedstr = reverseusingstringbuilder(original); system.out.println("reversed string: " + reversedstr); } public static string reverseusingstringbuilder(string str) { stringbuilder stringbuilder = new stringbuilder(str); stringbuilder.reverse(); return stringbuilder.tostring(); } }
文件输入/输出
import java.io.file; import java.io.filewriter; import java.io.filereader; import java.io.bufferedreader; import java.io.ioexception; public class main { public static void main(string[] args) { // write to file try (filewriter writer = new filewriter("example.txt")) { writer.write("hello, file i/o!n"); } catch (ioexception e) { e.printstacktrace(); } // read from file try (bufferedreader reader = new bufferedreader(new filereader("example.txt"))) { string line; while ((line = reader.readline()) != null) { system.out.println(line); } } catch (ioexception e) { e.printstacktrace(); } } }
异常处理
(注意: 捕获异常时,更具体的异常必须列在更一般的异常之前)
public class main { public static int divide(int a, int b) { if (b == 0) { throw new illegalargumentexception("division by zero"); } return a / b; } public static void main(string[] args) { try { int result = divide(10, 0); system.out.println("result: " + result); } catch (illegalargumentexception e) { system.out.println("error: " + e.getmessage()); } } }
内部类
内部类是在另一个类中定义的类。
- 会员内部类 成员内部类与外部类的实例相关联。它可以访问外部类的实例变量和方法。
public class outerclass { private string outerfield = "outer field"; class innerclass { void display() { system.out.println("accessing outer field: " + outerfield); } } public static void main(string[] args) { outerclass outer = new outerclass(); outerclass.innerclass inner = outer.new innerclass(); inner.display(); } }
- 静态嵌套类 静态嵌套类是在另一个类中定义的静态类。它无权访问外部类的实例成员,但可以访问其静态成员。
public class outerclass { private static string staticfield = "static field"; static class staticnestedclass { void display() { system.out.println("accessing static field: " + staticfield); } } public static void main(string[] args) { outerclass.staticnestedclass nested = new outerclass.staticnestedclass(); nested.display(); } }
- 本地内部类 局部内部类在块或方法内定义,并且可以访问局部变量(必须是最终的或实际上最终的)和外部类的成员。
public class outerclass { void method() { final string localvariable = "local variable"; class localinnerclass { void display() { system.out.println("accessing local variable: " + localvariable); } } localinnerclass localinner = new localinnerclass(); localinner.display(); } public static void main(string[] args) { outerclass outer = new outerclass(); outer.method(); } }
- 匿名内部类 匿名内部类是一种没有名称的内部类。 它可以精确地扩展一个类或精确地实现一个接口
class baseclass { void display() { system.out.println("baseclass display()"); } } public class main { public static void main(string[] args) { baseclass obj = new baseclass() { @override void display() { system.out.println("anonymous inner class display()"); } }; obj.display(); } }
拉姆达表达式
import java.util.arraylist; import java.util.list; public class main { public static void main(string[] args) { list<integer> nums = new arraylist(); nums.add(1); nums.add(2); nums.add(3); nums.add(4); nums.add(5); nums.replaceall(n -> n * 2); for (int num : nums) { system.out.print(num + " "); } system.out.println(); } } </integer>
switch 语句
public class main { public static void main(string[] args) { int day = 3; switch (day) { case 1: system.out.println("monday"); break; case 2: system.out.println("tuesday"); break; case 3: system.out.println("wednesday"); break; case 4: system.out.println("thursday"); break; case 5: system.out.println("friday"); break; case 6: system.out.println("saturday"); break; case 7: system.out.println("sunday"); break; default: system.out.println("invalid day"); break; } } }
普通指针
java 不像 c++ 那样使用显式指针;
小写和大写:
public class Main { public static void main(String[] args) { String str1 = "Hello, World!"; String str2= "HELLO, WORLD!"; String lowerStr = str2.toLowerCase(); String upperStr = str1.toUpperCase(); System.out.println(lowerStr); // Output: hello, world! System.out.println(upperStr); // Output: HELLO, WORLD! } }
以上就是Java 代码片段:)的详细内容,更多请关注php中文网其它相关文章!