---
# System prepended metadata

title: Java — Class(三) — Project(2)
tags: [教學, java]

---

Java — Class(三) — Project(2)
===

## **繼承(inheritance)**

class可以被繼承,其繼承者可以擁有它的method,property,但需注意是否有權去存取(封裝等級),java中的class拒絕多重繼承,欲使用多重繼承則要用interface.

繼承方法:extends
```java
//cat 繼承 animal
public classs cat extends animal
```


For instance:
```java
public class animal
{
    public String name;
    private int weight;
    
    protected int get_weight()
    {
        return this.weight;
    }
}

public calss cat extends animal
{
    public void Who()
    {
        System.out.println("I am :" + super.name);
    }
    
    public static void main(String arg[])
    {
        cat c1 = new cat()
        int w = c1.get_weight();
    }
}
```

## super,this用法

* **this** :每個class被編譯後都會有this物件,用來表示自己,常被使用在給class設定初使值.
```java=
class cat
{
    pulbic String name ;
    int weight ;
    
    public cat(String name,int weight)
    {
        this.name = name ;
        this.weight = weight;
    }
}

```
* **super** :與this用法大致上相同,不過是用來指向你的父class
```java=
class animal 
{
    pulbic String name ;
    int weight ;
    
    publci animal(String name)
    {
        this.name = name ;
    }
    public animal(String name,int weight)
    {
        this.name = name ;
        this.weight = weight;
    }
}

class cat extends animal
{
    public int hungry_rate ;
    
    public cat(String name)
    {
        super(name);
    }
    
    public cat(String name,int weight)
    {
       super(name,weight);
    }
    
     public cat(String name,int weigh,int hun)
    {
       super(name,weight);
       this.hungry_rate =hun ;
    }
    
}
```


###### tags: `java` `教學` 