Home  >  Article  >  Java  >  Java classes, encapsulation, inherited methods

Java classes, encapsulation, inherited methods

王林
王林forward
2023-04-28 11:19:14855browse

What is a class member

Member methods and member variables modified with static are called class members

Member variables modified with static are called class variables

Use static modification Member methods are called class methods

What are instance variables

Member methods and member variables that are not modified with static are called instance members

Member variables that are not modified with static are called Instance variables

Member methods that are not modified with static are called instance methods

For example:

public String name;  //这个就是实例成员(属性) 
public static int age;//这个就是类成员(属性) 

public void a(){
	System.out.println("我叫:"+this.name)
}                                    //这个没有加static的方法就是实例方法

public static void a(){           	//这个加了static的方法就是类方法
	System.out.println("我叫:"+this.name)
}

So what is the difference between instance variables and class variables?

  • All objects of this class share the same class variable, but each object will have its own unique instance variable

  • All objects of this class Objects can change the value of class variables, but each object can only change the value of its own instance variable

  • Instance variables must create an object before using them, and use them according to the object name.Variable name , but class variables do not need to create objects

//定义一个类
public class stu {
    public String name;  //这个类有一个名字这个属性,属于实例成员,也就是需要实例化对象了才可以使用
    //定义构造方法
    public stu(){}    //不管怎么样,都定义一个无参构造
    public stu(String name){    //定义有参构造,需要传入一个字符串名字
       this.name = name;         //这里若不使用this 关键字,那么是不会与上面的实例属性匹配
    }
    //定义方法
    public void a(){
        System.out.println(this.name);
    }
}

Use this class:

public class stu_Test {
    public static void main(String[] args) {
        //实例化两个对象,基于stu类
        stu s1 = new stu("小红");   
        stu s2 = new stu("小王");
        //使用stu类里面的方法
        s1.a();
        s2.a();
    }
    
    //stu s1 = new stu("小红");  将会输出小红
    //stu s2 = new stu("小王");  将会输出小王
}
//通过这个就可以明白每个对象都有属于自己的实例变量(属性)

So what is the difference between class methods and instance methods?

  • All objects of this class share class methods and instance methods

  • The class method can be called using the class name.method name ([parameter]) , there is no need to instantiate the object and use it

  • The instance method uses the object name.Method name ([parameter]) to call

static keyword

Java classes provide two types of variables: static variables modified with the static keyword and instance variables modified without the static keyword. Static variables belong to classes and have only one copy in memory. As long as the class where the static variable is located is loaded, the static variable will be allocated space, so it can be used. There are two ways to reference static variables, namely "class.static variable" and "object.static variable"

static member method:

  • static method is Class methods can be called without creating an object, while non-static methods are object methods and can only be used after the object is created.

  • This cannot be used in static methods With the super keyword, non-static methods cannot be called, and only static member variables and member methods of the class can be accessed, because when the static method is called, the object of this class may not have been created yet, and even if it has been created, it cannot Determines which object's method to call.

static use:

  • Modify member variables

  • Modify member methods

  • Static code block

  • Modified class [Only internal classes can be modified, that is, static internal classes]

  • Static import Package

static Notes: Static can only access static, non-static can access both non-static and static.

Encapsulation:

The concept of encapsulation

Encapsulates objective things into abstract classes, and classes can only allow trusted classes or objects to use their own properties and methods. Operations are hidden from untrusted classes or objects. This process is called encapsulation. In short: Seal your information and only show it to people you trust and use

Encapsulated classification

  • Encapsulation of attributes: Set attributes is private (private), restricting its use only within the class

  • Encapsulation of methods: For method encapsulation, set the externally accessible method to public, and set the externally inaccessible method to public. The method is set to private

Use of encapsulation

Before encapsulating, we first learn a new modifier: private private: restrict it to only the class Internal use (that is to say, the methods and attributes modified by private can only be discovered and used within this class, and the existence of this attribute cannot be found outside this class, which also achieves the effect of encapsulation)

//给name这个属性进行封装
private Strint name; //即可,这也我们在类外是找不到这个属性的存在的

Since it is encapsulated, there must be ways to modify and use this encapsulation. Yes, this is the get/set method

get/set method

public class stu {
    private String name; 
    public void setName(String name){    //set方法:对象调用这个方法,即可对私有属性进行修改
        this.name = name;   
    }
    public String getName(){         //get方法:对象调用这个方法,就可以使用该方法
        return name;
    }
}

Use:

public class stu_Test {
    public static void main(String[] args) {
    stu s =new stu();
    s.setName("小红");  //给name 这个私有属性修改值为小红
        System.out.println(s.getName());
   
}

//After the program runs, the output value is Xiaohong

Inheritance:

What is inheritance

1: A new Classes can be derived from existing classes. This process is called inheritance

2: During the inheritance process, the new class is called a subclass, the existing class is called a parent class, and the subclass will Inherit the properties and behavior of the parent class.

Inheritance syntax:

public class stu extends Student{   //在类名后加上extends,在写上继承的父类即可
//这里可以写父类没有发属性及方法
	public String ID;  //等等等等

}

Note: Inheritance cannot inherit the private properties and methods of the parent class! ! ! As long as it is modified by private, it will not be inherited! ! !

About subclasses: In addition to having the non-private properties and methods of the parent class, subclasses can also extend their own properties and methods

Use of inheritance:

  • Inheritance is single inheritance, that is, a class can only have one parent class.

  • If a class does not explicitly inherit a class, then it has a default parent class which is the java.lang.Object class

  • Inherits the non-private member variables and member methods of the parent class, but please note: the subclass cannot inherit the constructor method of the parent class

In short: a subclass only Can inherit a parent class. If this class does not inherit other classes, it will inherit the Object class by default (comes with Java)

The construction method of the parent class cannot be inherited.

方法的重写:

@overriding

什么是方法重写?:

  • 子类根据需求从父类继承的方法进行重新编写(方法名一样)

  • 重写是可以使用super方法的方式来保留父亲的方法(super在后面讲到)

注意:构造方法不能被重写

方法重写的规则:

  • 方法名相同,参数列表相同(数量,顺序,数据类型)

  • 如果有返回值,返回值相同或者是其子类,访问权限不能严于父类

  • 父类的静态方法不能被重写为非静态方法,反之父类的非静态方法不能被重写为静态方法

  • 子类可以定义与父类同名的静态方法,以便在子类中隐藏父类的静态方法**(静态方法中无法使用super、this)**

  • 父类的私有方法不能被子类重写(private修饰的)

上代码:

1:定义一个类,有名字和年龄的属性,分别有get/set方法,成员方法是输出名字和年龄:

public class Person {
    private String name;
    private int age;

    //get/ste方法
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }

    public void setAge(int age){
        this.age = age;
    }
    public int getAge(){
        return age;
    }
    //成员方法:
    public void print(){
        System.out.println("我叫:"+this.name+","+"我今年:"+this.age+"岁");
    }
}

2:写一个类,继承Person类,并且这个类拥有自己的一个sex属性,提供get/set方法 并且重写父类的print方法,输出名字+年龄+性别

public class child extends Person{
    private String sex;      //这个child类继承了Person类,但也拥有自己的属性 sex性别
    public void setSex(String sex){
        this.sex = sex;
    }
    public String getSex(){
        return sex;
    }
    @Override
    //重写父类方法: 因为父类是输出名字和年龄,这里要输出名字,年龄和性别
    public void print(){
        System.out.println("我叫:"+getName()+","+"我今年:"+getAge()+"岁"+","+"我是"+sex+"孩子");
    }
}

3:新建测试类,测试两个类的继承、重写

//测试类,
public class Test {
    public static void main(String[] args) {
        child c = new child();
        c.setName("小红");
        c.setAge(20);
        c.setSex("男");
        c.print();
    }
}
//分别执行child继承person的set方法,使用重写后的方法,

//输出结果为: 我叫:小红,我今年:20岁我是男孩子

super关键字:

super代表的是父类对象

super的使用方式:

1:super.属性名 用于在子类中调用父类被隐藏的同名实例变量

2:super([参数列表]) 用于在子类的构造方法中调用父类的构造方法

注意事项:

  • 每一个子类的构造方法在没有显示调用super(),系统都会提供一个默认的super()

  • super() 书写在第一行

  • 可以在子类构造方法中显示调用super(),完成对特定父类构造方法的调用

简而言之:super就是调用父亲的属性和方法来使用

上代码:

1:新建一个类:定义age为20

public class super_test {
    public int age=20;
    public void print(){
        System.out.println(this.age);
    }
}

2:建第二个类,继承第一个类;

public class su2 extends super_test{
    public int age = 10;
    @Override
    public void print(){
        System.out.println(super.age);  //这里使用super,意思是使用父类的age
    }
}

3:建立测试类:

public class test {
    public static void main(String[] args) {
    su2 s = new su2();
    s.print();
	}
}

这样输出的就是20,是父类的age Java classes, encapsulation, inherited methods

this与super的区别:

  • super: 它引用当前对象的直接父类中的成员(用来访问直接父类中被隐藏的父类中成员数据或函 数,基类与派生类中有相同成员定义时如:super.变量名 super.成员函数据名(实参)

  • this:它代表当前对象名(在程序中易产生二义性之处,应使用this来指明当前对象;如果函数的 形参与类中的成员数据同名,这时需用this来指明成员变量名

  • super()和this()类似,区别是,super()在子类中调用父类的构造方法,this()在本类内调用本类的其 它构造方法。

  • super()和this()均需放在构造方法内第一行,尽管可以用this调用一个构造器,但却不能调用两个

  • this和super不能同时出现在一个构造函数里面,因为this必然会调用其它的构造函数,其它的构造 函数必然也会有super语句的存在,所以在同一个构造函数里面有相同的语句,就失去了语句的意 义,编译器也不会通过。

  • this()和super()都指的是对象,所以,均不可以在static环境中使用。包括: static变量,static方法,static语句块。

  • 从本质上讲,this是一个指向本对象的指针, 然而super是一个Java关键字。

The above is the detailed content of Java classes, encapsulation, inherited methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete