专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

类与对象(类、对象、对象的比较)

类:是对某一事物的抽象描述,通过方法(成员方法)和属性(成员变量)来描述事物。

对象:对象是实际存在的该类事物的个体,因而也称实例。

1、类与对象

创建圆类:

 package Circle;

 public class Circle {
 public double  Pi=3.1415926;
 public double radius;//属性
 public Circle(double radius){//方法
     this.radius=radius;
 }
 public double getRadius(){
    return radius; 
 }

 public void updateRadius(double radius){
    this.radius=radius;
 }

 public void getArea(){
     System.out.println("圆的面积:"+radius*radius*Pi);
 }
 }

创建圆锥类:

 package Taper;
 public class Taper {
 double bottom;
 double height;
 public Taper(double bottom,double height){
     this.bottom=bottom;
     this.height=height;
 }
 public double getBottom(){
     return  bottom;
 }

 public double  getBottomR(){
     return Math.sqrt(bottom/3.1415926);
 }

 public double updateBottomR(double BottomR) {
      bottom=3.1415926*BottomR*BottomR; 
      return  bottom;
 }

 public double getHeight(){ 
     return height; 
 } 

 public void updateHeight(double height){ 
     this.height=height; 
 }

 public double volume(){ 
     return bottom*height/3; 
 }

 }

测试类:

 package Run;
 import Circle.Circle;
 import Taper.Taper;
 public class Test {
 public static void main(String args[]) {
     Circle cir=new Circle(2);//创建圆的对象
     System.out.println("圆的半径为:"+cir.getRadius());
     cir.getArea();
     cir.updateRadius(3);
     System.out.println("修改后圆的半径为:"+cir.getRadius());
     cir.getArea();    
     System.out.println("***********************");
     Taper tap=new Taper(34.1,21.3);//创建圆锥的对象
     System.out.println("锥体的底面积为:"+tap.getBottom());
     System.out.println("椎体的底面半径为:"+tap.getBottomR());
     System.out.println("更改后的椎体体积为:"+tap.updateBottomR(1));
 }
 }

(1)类是一个模板,它描述的是一类对象的行为和方法,例如:定义一个学生类,该类含有属性:学号、姓名、性别,方法:学习。即:类通过方法和属性描述一个学生类。

(2)对象是一个个体,类被实例化后产生一个对象,例如:对学生的属性赋值之后,该学生有学号、姓名、性别,在一般情况下可以确定一个学生。

2、对象的赋值与比较:

public class Compare {
    public static void main(String[] args) {
        String str1 = new String("abc");
        String str2 = new String("abc");//str1和str2是两个不同的对象,占用不同的内存空间
        String str3 = str1;//在栈内存中有相同的内存空间
        if (str1 == str2)//==比较的是两个对象的内存地址
            System.out.println("str1==str2");
        else
            System.out.println("str1!=str2");
        if (str1 == str3)
            System.out.println("str1==str3");
        else
            System.out.println("str1!=str3");
    }
}

35_1.png

虽然str1和str2的值相等,但是这是两个不同的对象,在内存中占用不同的空间。

文章永久链接:https://tech.souyunku.com/22676

未经允许不得转载:搜云库技术团队 » 类与对象(类、对象、对象的比较)

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们