Java inherited and definitions outlined examples

Overview inheritance

When the presence of the same properties and behavior of a plurality of classes, the extracted content to a single class, then the class without redefining a plurality of these properties and behavior, and that as long as a class can inherit.

In real life inherit: inherited his father used to describe the relationships between things

Inheritance tag: is used to describe the relationship between two classes, subclasses and parent class has member variables and member methods

Inherited definition

Inheritance : parent class is a subclass inherits the attributes and behavior , so that the subclass object having a parent with the same attributes, the same behavior. Subclass can directly access the parent class of non-private properties and behaviors.

Inherited format

By extendskeyword, you can declare a subclass inherits another parent class is defined in the following format:

class parent class { 
    ... 
} 

class subclass extends parent { 
    ... 
}

 

Inheritance code demonstrates the following code:

Employee defined class Employee, to do as a parent class

class the Employee { 
    String name; // definition of the name attribute
     // working methods defined employee 
    public  void Work () { 
        System.out.println ( "dedicated work" ); 
    } 
}

Lecturer defined class Employee Class Teacher inherit employees

class Teacher the extends the Employee {
     // definition of a printing method name 
    public  void printName () { 
        System.out.println ( "name =" + name); 
    } 
}

Defines the test class

public  class ExtendDemo01 {
     public  static  void main (String [] args) {
         // create a class object lecturer 
        Teacher T = new new Teacher (); 
      
        // assign employee name property class 
        t.name = "Bob" ; 
      
        / / invoke printName the employee () method 
        t.printName (); // name = Bob 
        
        // call the class inherited Teacher work () method 
        t.work ();   // dedicated work 
    } 
}

 

Guess you like

Origin www.cnblogs.com/libinhong/p/10990170.html