【Java 百“练”成钢】Java 基础:类和对象

  • Class):类是对具有共同特征的事物或事件的集合的抽象,它定义了一类对象的属性和方法。类是抽象的,不占用内存,但它提供了创建对象的蓝图或模板。类中的成员包括属性和方法,属性用于存储数据,而方法则定义了对象可以执行的操作。类是现实世界或思维世界中的实体在计算机中的反映,它将数据以及这些数据上的操作封装在一起。
  • 对象Object):对象是类的实例,即类的具体化。对象是具体的,占用存储空间,并且具有类的属性和行为。对象是通过类来创建的,每个对象都是类的一个独立实例,拥有自己的属性和状态。对象是对客观事物的抽象,它通过调用类的方法来执行操作。

01.打印信息

import java.util.*;

class Welcome {
    public void print_msg() {
        System.out.println("Welcome Java Exercise");
    }

    public static void main(String s[]) {
        Welcome obj = new Welcome();
        obj.print_msg();
    }
}

image.png

02.打印类的简单名称

public class Get_Name {
    public static void main(String[] args) throws ClassNotFoundException {
        Class cls = Class.forName("java.lang.String");

        System.out.println("Class Name Associated with cls : " + cls.getName());
        System.out.println("Simple Class Name Associated with cls : " + cls.getSimpleName());
    }
}

image.png

getName()

  • 返回该类对象作为字符串表示的实体(类、接口、数组类、基本数据类型或 void)的名称。
  • 可以理解为返回的是虚拟机中 Class 对象的表示。
  • 当我们动态加载类的时候,会用到该方法的返回值,如: 使用 Class.forName() 方法。
  • 如果是内部类,则使用 $ 符号进行连接。
  • 如果是数组,则使用 [ 来表示,数组是几维,[ 就有几个。
  • 其余情况的表示如下:

getSimpleName()

  • 返回源代码中给出的基础类的简单名称,如果基础类是匿名的,则返回空字符串。
  • 可以理解为返回的是仅仅是类名,不包含路径。
  • 不能保证能唯一标识一个类,可以在 toString() 或日志操作期间使用。

03.打印类的 ClassLoader

public class ClassLoader {
    public static void main(String[] args) throws ClassNotFoundException {
        Class c1 = Class.forName("ClassLoader");
        Class c2 = Class.forName("java.lang.String");
        Class c3 = int.class;

        System.out.println("Class loader associated with c1 : " + c1.getClassLoader());
        System.out.println("Class loader associated with c2 : " + c2.getClassLoader());
        System.out.println("Class loader associated with c3 : " + c3.getClassLoader());
    }
}

image.png

这是一个 Java 程序,演示如何使用getClassLoader()方法获取与类关联的类加载器。

main()方法中,程序使用Class.forName()方法获取与 ClassLoader 类关联的 Class 对象。它还获取与java.lang.Strin 类和int基元类型相关联的 Class 对象。int基元类型可以使用int.class作为类直接访问。

然后,该程序使用每个 Class 对象的getClassLoader()方法来获取与该类相关联的类加载器。类加载器使用println()方法打印到控制台

在 Java 中,java.lang.Class.getClassLoader()方法返回的是类加载器的类。一些实现可能使用 null 来表示引导类加载器。如果这个类是由引导类加载器加载的,那么在这样的实现中,该方法将返回 null。

getClassLoader()是获取当前的类加载器。什么是类加载器?简单点说,就是用来加载 Java 类的,类加载器负责把 class 文件加载进内存中,并创建一个java.lang.Class类的一个实例,也就是 class 对象,并且每个类的类加载器都不相同。

04.获取类的方法

import java.lang.reflect.Method;

public class ListMethods {
    public static void main(String[] args) throws ClassNotFoundException {
        Class cls = Class.forName("java.lang.Integer");

        Method methods[] = cls.getMethods();

        System.out.println("Methods of Integer class: ");
        for (Method m : methods) {
            System.out.println(m);
        }
    }
}

image.png

Methods of Integer class: 
public static int java.lang.Integer.numberOfLeadingZeros(int)
public static int java.lang.Integer.numberOfTrailingZeros(int)
public static int java.lang.Integer.bitCount(int)
public boolean java.lang.Integer.equals(java.lang.Object)
public static java.lang.String java.lang.Integer.toString(int,int)
public java.lang.String java.lang.Integer.toString()
public static java.lang.String java.lang.Integer.toString(int)
public static int java.lang.Integer.hashCode(int)
public int java.lang.Integer.hashCode()
public static int java.lang.Integer.min(int,int)
public static int java.lang.Integer.max(int,int)
public static int java.lang.Integer.reverseBytes(int)
public int java.lang.Integer.compareTo(java.lang.Integer)
public int java.lang.Integer.compareTo(java.lang.Object)
public byte java.lang.Integer.byteValue()
public short java.lang.Integer.shortValue()
public int java.lang.Integer.intValue()
public long java.lang.Integer.longValue()
public float java.lang.Integer.floatValue()
public double java.lang.Integer.doubleValue()
public static java.lang.Integer java.lang.Integer.valueOf(java.lang.String,int) throws java.lang.NumberFormatException
public static java.lang.Integer java.lang.Integer.valueOf(int)
public static java.lang.Integer java.lang.Integer.valueOf(java.lang.String) throws java.lang.NumberFormatException
public static java.lang.String java.lang.Integer.toHexString(int)
public static int java.lang.Integer.compare(int,int)
public static java.lang.Integer java.lang.Integer.decode(java.lang.String) throws java.lang.NumberFormatException
public static int java.lang.Integer.reverse(int)
public static int java.lang.Integer.sum(int,int)
public static int java.lang.Integer.parseInt(java.lang.String) throws java.lang.NumberFormatException
public static int java.lang.Integer.parseInt(java.lang.String,int) throws java.lang.NumberFormatException
public static long java.lang.Integer.toUnsignedLong(int)
public static int java.lang.Integer.compareUnsigned(int,int)
public static int java.lang.Integer.divideUnsigned(int,int)
public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String,java.lang.Integer)
public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String,int)
public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String)
public static int java.lang.Integer.highestOneBit(int)
public static int java.lang.Integer.lowestOneBit(int)
public static int java.lang.Integer.parseUnsignedInt(java.lang.String) throws java.lang.NumberFormatException
public static int java.lang.Integer.parseUnsignedInt(java.lang.String,int) throws java.lang.NumberFormatException
public static int java.lang.Integer.remainderUnsigned(int,int)
public static int java.lang.Integer.rotateLeft(int,int)
public static int java.lang.Integer.rotateRight(int,int)
public static int java.lang.Integer.signum(int)
public static java.lang.String java.lang.Integer.toBinaryString(int)
public static java.lang.String java.lang.Integer.toOctalString(int)
public static java.lang.String java.lang.Integer.toUnsignedString(int)
public static java.lang.String java.lang.Integer.toUnsignedString(int,int)
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()

05.获取类的Package

public class GetPackage {
    public static void main(String[] args) throws ClassNotFoundException {
        Class c1 = Class.forName("java.util.Set");
        Class c2 = Class.forName("java.lang.String");

        System.out.println("Package Names .. ");
        System.out.println(c1.getPackage());
        System.out.println(c2.getPackage());
    }
}

image.png

06.创建一个对象数组

class ArrayObject {
    public static void main(String args[]) {
        Sample[] arrobj = new Sample[5];

        arrobj[0] = new Sample();
        arrobj[1] = new Sample();
        arrobj[2] = new Sample();
        arrobj[3] = new Sample();
        arrobj[4] = new Sample();

        arrobj[0].sayHello();
        arrobj[1].sayHello();
        arrobj[2].sayHello();
        arrobj[3].sayHello();
        arrobj[4].sayHello();
    }
}

class Sample {
    void sayHello() {
        System.out.println("Java Exercise");
    }
}

image.png

07.计算圆的面积

import java.util.*;

public class Area_Circle {
    public static void main(String[] args) {
        AreaOfCircle area = new AreaOfCircle();

        area.readRadius();
        System.out.println("Area of Circle : " + area.getArea());
    }
}

class AreaOfCircle {
    private float rad = 0.0f;
    private float area = 0.0f;

    public void readRadius() {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the Radius : ");
        rad = input.nextFloat();
    }

    public float getArea() {
        area = (float) Math.PI * rad * rad;
        return area;
    }
}

image.png

input.nextInt() 表示接收 int 型数据;input.nextFloat() 表示接收 float 型数据。

08.计算圆的周长

import java.util.*;

public class Perimeter_Circle {
    public static void main(String args[]) {
        PerimeterOfCircle area = new PerimeterOfCircle();

        area.readRadius();
        System.out.println("Perimeter of Circle : " + area.getPerimeter());
    }
}

class PerimeterOfCircle {
    private float rad = 0.0f;
    private float peri = 0.0f;

    public void readRadius() {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the Radius : ");
        rad = input.nextFloat();
    }

    public float getPerimeter() {
        peri = 2 * (float) Math.PI * rad;
        return peri;
    }
}

image.png

09.创建具有私有访问修饰符的成员

public class Member_Private {
    public static void main(String[] args) {
        Demo d = new Demo();

        //statement will generate an error We cannot access private member outside the class.
        //System.out.println("Number 1 : "+d.num1);
        //System.out.println("Number 2 : "+d.num2);
        d.printValues();
    }
}

class Demo {
    private int num1 = 12;
    private int num2 = 20;

    void printValues() {
        System.out.println("Number 1 : " + num1);
        System.out.println("Number 2 : " + num2);
    }
}

image.png

10.创建带访问修饰符的成员

public class Create_Members {
    public static void main(String[] args) {
        Demo d = new Demo();
        d.printValues();

        // accessed outside the class.
        System.out.println("Number 1 : " + d.num1);
        System.out.println("Number 2 : " + d.num2);
    }
}

class Demo {
    int num1 = 10;
    int num2 = 20;

    void printValues() {
        System.out.println("Number 1 : " + num1);
        System.out.println("Number 2 : " + num2);

        num1 = 30;
        num2 = 40;
    }
}

image.png

11.将对象作为参数传递

class PassObject {
    public static void main(String args[]) {
        Sample o1 = new Sample();
        Sample o2 = new Sample();
        o1.setNum(10);
        o2.setNum(20);

        int res = o1.add_Object(o2);
        System.out.println("Addition : " + res);
    }
}

class Sample {
    int num;

    void setNum(int n) {
        num = n;
    }

    int add_Object(Sample obj) {
        int add = 0;
        add = num + obj.num;
        return add;
    }
}

image.png

12.通过类对象获取类名

public class GetClass_Name {
    public static void main(String[] args) {
        GetClass_Name o = new GetClass_Name();
        System.out.println("Print class Name : " + o.getClass());
    }
}

image.png

13.将一个类的对象创建为另一个类的数据成员

public class Create_Object {
    public static void main(String[] args) {
        Student emp = new Student(101, "Joes", 32);
        emp.printEmployeeDetails();
    }
}

class Person {
    String name;
    int age;

    Person(int age, String name) {
        this.name = name;
        this.age = age;
    }
}

class Student {
    int stu_id;
    int stu_per;
    Person P;

    Student(int id, String name, int age) {
        P = new Person(age, name);
        stu_id = id;
    }

    void printEmployeeDetails() {
        System.out.println("Student ID     :  " + stu_id);
        System.out.println("Student Name   :  " + P.name);
        System.out.println("Student Age    :  " + P.age);
    }
}

image.png

14.实现默认构造函数

class Default_Constructor {
    public static void main(String args[]) {
        Demo d = new Demo();
        d.printValues();
    }
}

class Demo {
    int n1;
    int n2;

    Demo() {
        n1 = 10;
        n2 = 20;
    }

    void printValues() {
        System.out.println("Number 1 : " + n1);
        System.out.println("Number 2 : " + n2);
    }
}

image.png

15.实现有参构造函数

class Parameterized_Constructor {
    public static void main(String args[]) {
        Demo d = new Demo(30, 40);
        d.printValues();
    }
}

class Demo {
    int n1;
    int n2;

    Demo(int num1, int num2) {
        n1 = num1;
        n2 = num2;
    }

    void printValues() {
        System.out.println("Number 1 : " + n1);
        System.out.println("Number 2 : " + n2);
    }
}

image.png

16.构造函数重载

class Constructor_Overloading {
    public static void main(String args[]) {
        Demo o1 = new Demo();
        Demo o2 = new Demo(300, 400);

        o1.printValues();
        o2.printValues();
    }
}

class Demo {
    int num1;
    int num2;

    Demo() {
        num1 = 100;
        num2 = 200;
    }

    Demo(int n1, int n2) {
        num1 = n1;
        num2 = n2;
    }

    void printValues() {
        System.out.println("Number 1 : " + num1);
        System.out.println("Number 2 : " + num2);
    }
}

image.png

17.复制构造函数

class Copy_Constructor {
    public static void main(String args[]) {
        Demo o1 = new Demo(10, 15);
        Demo o2 = new Demo(o1);

        o1.printValues();
        System.out.println("Copy Constructor..");
        o2.printValues();
    }
}

class Demo {
    int num1;
    int num2;

    Demo(int n1, int n2) {
        this.num1 = n1;
        this.num2 = n2;
    }

    Demo(Demo obj) {
        this.num1 = obj.num1;
        this.num2 = obj.num2;
    }

    void printValues() {
        System.out.println("Number 1 : " + num1);
        System.out.println("Number 2 : " + num2);
    }
}

image.png

18.instanceof 操作符

public class Demo {
    public static void main(String[] args) {
        Demo d = new Demo();
        boolean res = d instanceof Demo;
        if (res) {
            System.out.println("Object d is an instance of Demo class");
        } else {
            System.out.println("Object d is not an instance of Demo class");
        }
    }
}

image.png

19.创建匿名对象

public class Anonymous {
    public static void main(String[] args) {
        new Demo();
    }
}

class Demo {
    Demo() {
        System.out.println("Constructor");
    }
}

image.png

什么是匿名对象?

  • 顾名思义就是没有变量名的对象,即创建对象时,只有创建对象的语句,却没有把对象地址值赋值给某个变量。
  • 匿名对象命名格式: 以 Scanner 类举例,new Scanner(System.in);
  • 由于匿名对象没有变量名所以其也只可以使用一次。
public class Test {
    public static void main(String[] args) {
        int i = new Scanner(System.in).nextInt();
        System.out.println(i);
    }
}

Java 匿名对象是没有明确引用的对象,通常用于以下几种情况:

  • 当调用某个方法一次且仅一次时,如工具类方法。
  • 当传递参数时,不需要保持对新创建对象的引用。
  • 当在接口上使用 Lambda 表达式时,接口可能只有一个抽象方法,这种情况下可以使用匿名对象。

20.单例类

编写一个 Java 程序,创建一个方法名称与类名称相同的单例类。

class Create_Singleton {
    public static void main(String args[]) {
        Singleton o1 = Singleton.Singleton();
        Singleton o2 = Singleton.Singleton();
        Singleton o3 = Singleton.Singleton();

        if (o1 == o2 && o1 == o3) {
            System.out.println("All object are pointing to the same memory location.");
        } else {
            System.out.println("All object are not pointing to the same memory location.");
        }
    }
}

class Singleton {
    private static Singleton singleRef = null;

    private Singleton() {
    }

    public static Singleton Singleton() {
        if (singleRef == null) {
            singleRef = new Singleton();
        }
        return singleRef;
    }
}

image.png

21.使用匿名对象调用方法

public class Anonymous_Object {
    public static void main(String args[]) {
        new Demo().printHello();
    }
}

class Demo {
    void printHello() {
        System.out.println("Hello World");
    }

    Demo() {
        System.out.println("Constructor");
    }
}

image.png

22.使用匿名对象调用静态 Block

public class CallStatic_Block {
    static {
        System.out.println("Static Block 1");
    }

    public static void main(String[] args) {
        new Demo();
    }

    static {
        System.out.println("Static Block 2");
    }
}

class Demo {
    static {
        System.out.println("Static Block 3");
    }

    Demo() {
        System.out.println("Constructor");
    }

    static {
        System.out.println("Static Block 4");
    }
}

image.png

static 块会在类被加载的时候执行且仅会被执行一次,一般用来初始化静态变量和调用静态方法。

  • 当一个类中有多个 static{} 的时候,按照 static{} 的定义顺序,从前往后执行。
  • 先执行完 static{} 语句块的内容,才会执行调用语句。
  • 如果静态变量在定义的时候就赋给了初值,如 static int X=100,那么赋值操作也是在类加载的时候完成的,并且当一个类中既有 static{} 又有 static 变量的时候,同样遵循 “先定义先执行” 的原则;

23.检查匿名类

public class Check_Anonymous {
    public static void main(String[] args) {
        Class<? extends Object> cls = new Object() {}.getClass();
        boolean res = cls.isAnonymousClass();

        if (res) {
            System.out.println("It is an Anonymous Class");
        } else {
            System.out.println("It is Not an Anonymous Class");
        }
    }
}

image.png

  • main() 方法使用 new Object() {} 语法创建了一个新的匿名类,它创建了一个 Object 类的新对象,但没有明确定义类名。然后在新对象上调用getClass()方法,获取其 Class 对象。
  • 然后在 Class 对象上调用 isAnonymousClass() 方法,如果该类是匿名类,则返回 true,否则返回 false
  • 最后,程序会根据 isAnonymousClass() 返回的值向控制台打印一条信息,说明该类是否为匿名类。
  • 这是因为 new Object() {} 语法创建了一个扩展 Object 的匿名类实例,调用 isAnonymousClass() 可以确认这一点。
  • 17
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

G皮T

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值