java继承的范例_Java范例中的继承

java继承的范例

Inheritance in java is one of the core concepts of Object Oriented Programming. Java Inheritance is used when we have is-a relationship between objects. Inheritance in Java is implemented using extends keyword.

Java中的继承是面向对象编程的核心概念之一。 Java的继承是在使用时我们已经是-一个对象之间的关系。 Java中的继承是使用extends关键字实现的。

Java中的继承 (Inheritance in Java)

Inheritance in Java is the method to create a hierarchy between classes by inheriting from other classes.

Java中的继承是一种通过从其他类继承来在类之间创建层次结构的方法。

Java Inheritance is transitive – so if Sedan extends Car and Car extends Vehicle, then Sedan is also inherited from Vehicle class. The Vehicle becomes the superclass of both Car and Sedan.

Java继承是可传递的-因此,如果Sedan extends CarCar extends Vehicle ,则Sedan也将从Vehicle类继承。 车辆成为轿车和轿车的超类。

Inheritance is widely used in java applications, for example extending Exception class to create an application specific Exception class that contains more information like error codes. For example NullPointerException.

继承在Java应用程序中被广泛使用,例如,扩展Exception类以创建特定于应用程序的Exception类,该类包含更多信息,例如错误代码。 例如NullPointerException 。

Java继承示例 (Java Inheritance Example)

Every class in java implicitly extends java.lang.Object class. So Object class is at the top level of inheritance hierarchy in java.

java中的每个类都隐式扩展了java.lang.Object类。 因此,Object类是Java中继承层次结构的顶层。

Let’s see how to implement inheritance in java with a simple example.

让我们来看一个简单的示例,如何在Java中实现继承。

Superclass: Animal

超类:动物

package com.journaldev.inheritance;

public class Animal {

	private boolean vegetarian;

	private String eats;

	private int noOfLegs;

	public Animal(){}

	public Animal(boolean veg, String food, int legs){
		this.vegetarian = veg;
		this.eats = food;
		this.noOfLegs = legs;
	}

	public boolean isVegetarian() {
		return vegetarian;
	}

	public void setVegetarian(boolean vegetarian) {
		this.vegetarian = vegetarian;
	}

	public String getEats() {
		return eats;
	}

	public void setEats(String eats) {
		this.eats = eats;
	}

	public int getNoOfLegs() {
		return noOfLegs;
	}

	public void setNoOfLegs(int noOfLegs) {
		this.noOfLegs = noOfLegs;
	}

}

The Animal is the base class here. Let’s create a Cat class that inherits from Animal class.

动物是这里的基类。 让我们创建一个从Animal类继承的Cat类。

Subclass: Cat

子类别:猫

package com.journaldev.inheritance;

public class Cat extends Animal{

	private String color;

	public Cat(boolean veg, String food, int legs) {
		super(veg, food, legs);
		this.color="White";
	}

	public Cat(boolean veg, String food, int legs, String color){
		super(veg, food, legs);
		this.color=color;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

}

Notice that we are using extends keyword to implement inheritance in java.

注意,我们使用extends关键字在java中实现继承。

Java Inheritance Test Program

Java继承测试程序

Let’s write a simple test class to create Cat object and use some of its methods.

让我们编写一个简单的测试类来创建Cat对象并使用其某些方法。

package com.journaldev.inheritance;

public class AnimalInheritanceTest {

	public static void main(String[] args) {
		Cat cat = new Cat(false, "milk", 4, "black");

		System.out.println("Cat is Vegetarian?" + cat.isVegetarian());
		System.out.println("Cat eats " + cat.getEats());
		System.out.println("Cat has " + cat.getNoOfLegs() + " legs.");
		System.out.println("Cat color is " + cat.getColor());
	}

}

Java继承程序输出 (Java Inheritance Program Output)

Output of the above program is shown in below image.

下图显示了上述程序的输出。

Cat class doesn’t have getEats() method but still it works because it’s inherited from Animal class.

Cat类没有getEats()方法,但仍然有效,因为它是从Animal类继承的。

Java继承要点 (Java Inheritance Important Points)

  1. Code reuse is the most important benefit of inheritance because subclasses inherits the variables and methods of superclass.

    代码重用是继承的最重要好处,因为子类继承了超类的变量和方法。
  2. Private members of superclass are not directly accessible to subclass. As in this example, Animal variable noOfLegs is not accessible to Cat class but it can be indirectly accessible via getter and setter methods.

    子类不能直接访问超类的私有成员。 如本例所示,Cat类无法访问Animal变量noOfLegs,但可以通过getter和setter方法间接访问。
  3. Superclass members with default access is accessible to subclass ONLY if they are in same package.

    具有默认访问权限的超类成员只有在同一个程序包中才能被子类访问。
  4. Superclass constructors are not inherited by subclass.

    父类不继承超类的构造函数 。
  5. If superclass doesn’t have default constructor, then subclass also needs to have an explicit constructor defined. Else it will throw compile time exception. In the subclass constructor, call to superclass constructor is mandatory in this case and it should be the first statement in the subclass constructor.

    如果超类没有默认的构造函数,则子类也需要定义一个显式的构造函数。 否则将抛出编译时异常。 在子类构造函数中,在这种情况下,必须调用超类构造函数,并且它应该是子类构造函数中的第一条语句。
  6. Java doesn’t support multiple inheritance, a subclass can extends only one class. Animal class is implicitly extending Object class and Cat is extending Animal class but due to java inheritance transitive nature, Cat class also extends Object class.

    Java不支持多重继承 ,子类只能扩展一个类。 Animal类隐式地扩展了Object类,Cat类扩展了Animal类,但是由于java继承的传递性,Cat类也扩展了Object类。
  7. We can create an instance of subclass and then assign it to superclass variable, this is called upcasting. Below is a simple example of upcasting:
    Cat c = new Cat(); //subclass instance
    Animal a = c; //upcasting, it's fine since Cat is also an Animal

    我们可以创建子类的实例,然后将其分配给超类变量,这称为upcasting 。 以下是上播的简单示例:
  8. When an instance of Superclass is assigned to a Subclass variable, then it’s called downcasting. We need to explicitly cast this to Subclass. For example;
    Cat c = new Cat();
    Animal a = c;
    Cat c1 = (Cat) a; //explicit casting, works fine because "c" is actually of type Cat

    Note that Compiler won’t complain even if we are doing it wrong, because of explicit casting. Below are some of the cases where it will throw ClassCastException at runtime.

    当将Superclass的实例分配给Subclass变量时,则称为downcasting 。 我们需要将其显式转换为Subclass。 例如;
    Cat c = new Cat();
    Animal a = c;
    Cat c1 = (Cat) a; //explicit casting, works fine because "c" is actually of type Cat

    注意,由于显式转换,即使我们做错了,编译器也不会抱怨。 在某些情况下,它将在运行时引发ClassCastException

  9. We can override the method of Superclass in the Subclass. However we should always annotate overridden method with @Override annotation. The compiler will know that we are overriding a method and if something changes in the superclass method, we will get a compile-time error rather than getting unwanted results at the runtime.

    我们可以在子类中重写Superclass的方法。 但是,我们应该始终使用@Override注解注释覆盖的方法。 编译器将知道我们正在重写一个方法,并且如果超类方法发生了某些变化,我们将得到一个编译时错误,而不是在运行时得到不想要的结果。
  10. We can call the superclass methods and access superclass variables using super keyword. It comes handy when we have the same name variable/method in the subclass but we want to access the superclass variable/method. This is also used when Constructors are defined in the superclass and subclass and we have to explicitly call the superclass constructor.

    我们可以调用超类方法并使用super关键字访问超类变量。 当我们在子类中具有相同的名称变量/方法但我们要访问超类变量/方法时,它会派上用场。 当在超类和子类中定义构造函数并且我们必须显式调用超类构造函数时,也会使用此方法。
  11. We can use instanceof instruction to check the inheritance between objects, let’s see this with below example.
    Cat c = new Cat();
    Dog d = new Dog();
    Animal an = c;
    
    boolean flag = c instanceof Cat; //normal case, returns true
    
    flag = c instanceof Animal; // returns true since c is-an Animal too
    
    flag = an instanceof Cat; //returns true because a is of type Cat at runtime
    
    flag = an instanceof Dog; //returns false for obvious reasons.

    我们可以使用instanceof指令检查对象之间的继承,下面的示例让我们来看一下。
  12. We can’t extend Final classes in java.

    我们无法在Java中扩展Final类。
  13. If you are not going to use Superclass in the code i.e your Superclass is just a base to keep reusable code then you can keep them as Abstract class to avoid unnecessary instantiation by client classes. It will also restrict the instance creation of base class.

    如果您不打算在代码中使用超类,即您的超类只是保留可重用代码的基础,则可以将其保留为Abstract类,以避免客户端类不必要的实例化。 它还将限制基类的实例创建。

Java继承视频 (Java Inheritance Videos)

I have recently published two videos on YouTube explaining Inheritance in detail with sample programs, you should watch them below.

我最近在YouTube上发布了两个视频,其中通过示例程序详细解释了继承,您应该在下面观看。

演示地址

演示地址

GitHub Repository. GitHub Repository中检出更多继承示例。

Reference: Oracle Documentation

参考: Oracle文档

翻译自: https://www.journaldev.com/644/inheritance-java-example

java继承的范例

你可能感兴趣的:(java,编程语言,类,面向对象编程,object)