산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> java

자바 - 상속

상속은 한 클래스가 다른 클래스의 속성(메서드 및 필드)을 획득하는 프로세스로 정의할 수 있습니다. 상속을 사용하면 정보를 계층적 순서로 관리할 수 있습니다.

다른 사람의 속성을 상속하는 클래스를 하위 클래스(파생 클래스, 자식 클래스)라고 하고 속성을 상속받는 클래스를 슈퍼 클래스(기본 클래스, 부모 클래스)라고 합니다.

확장 키워드

확장 클래스의 속성을 상속하는 데 사용되는 키워드입니다. 다음은 extends 키워드의 구문입니다.

구문

class Super {
   .....
   .....
}
class Sub extends Super {
   .....
   .....
}

샘플 코드

다음은 Java 상속을 보여주는 예입니다. 이 예에서는 Calculation 및 My_Calculation이라는 두 가지 클래스를 관찰할 수 있습니다.

extends 키워드를 사용하여 My_Calculation은 Calculation 클래스의 add() 및 Subtraction() 메서드를 상속합니다.

My_Calculation.java

라는 이름의 파일에 다음 프로그램을 복사하여 붙여넣습니다.

라이브 데모
class Calculation {
   int z;
	
   public void addition(int x, int y) {
      z = x + y;
      System.out.println("The sum of the given numbers:"+z);
   }
	
   public void Subtraction(int x, int y) {
      z = x - y;
      System.out.println("The difference between the given numbers:"+z);
   }
}

public class My_Calculation extends Calculation {
   public void multiplication(int x, int y) {
      z = x * y;
      System.out.println("The product of the given numbers:"+z);
   }
	
   public static void main(String args[]) {
      int a = 20, b = 10;
      My_Calculation demo = new My_Calculation();
      demo.addition(a, b);
      demo.Subtraction(a, b);
      demo.multiplication(a, b);
   }
}

위의 코드를 아래와 같이 컴파일하여 실행합니다.

javac My_Calculation.java
java My_Calculation

프로그램을 실행하면 다음과 같은 결과가 나타납니다 -

출력

The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

주어진 프로그램에서 My_Calculation에 대한 개체가 클래스가 생성되면 슈퍼클래스 내용의 복사본이 그 안에 만들어집니다. 그렇기 때문에 하위 클래스의 개체를 사용하여 상위 클래스의 멤버에 액세스할 수 있습니다.

슈퍼클래스 참조 변수는 하위 클래스 개체를 보유할 수 있지만 이 변수를 사용하면 슈퍼클래스의 멤버에만 액세스할 수 있으므로 두 클래스의 멤버에 액세스하려면 항상 서브클래스에 대한 참조 변수를 생성하는 것이 좋습니다.

위의 프로그램을 고려한다면 아래와 같이 클래스를 인스턴스화할 수 있다. 그러나 슈퍼클래스 참조 변수( cal 이 경우) multiplication() 메서드를 호출할 수 없습니다. , 하위 클래스 My_Calculation에 속합니다.

Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);

참고 − 하위 클래스는 상위 클래스에서 모든 멤버(필드, 메서드 및 중첩 클래스)를 상속합니다. 생성자는 멤버가 아니므로 하위 클래스에 상속되지 않지만 상위 클래스의 생성자는 하위 클래스에서 호출할 수 있습니다.

슈퍼 키워드

슈퍼 키워드가 이것과 유사합니다. 예어. 다음은 super 키워드가 사용되는 시나리오입니다.

구성원 차별화

클래스가 다른 클래스의 속성을 상속하는 경우. 그리고 상위 클래스의 멤버가 하위 클래스와 이름이 같을 경우 이러한 변수를 구별하기 위해 아래와 같이 super 키워드를 사용합니다.

super.variable
super.method();

샘플 코드

이 섹션에서는 super 키워드.

주어진 프로그램에는 Sub_class라는 두 개의 클래스가 있습니다. 및 Super_class , 둘 다 구현이 다른 display()라는 메서드와 값이 다른 num이라는 변수가 있습니다. 두 클래스의 display() 메서드를 호출하고 두 클래스의 변수 num 값을 인쇄합니다. 여기에서 super 키워드를 사용하여 슈퍼클래스의 멤버를 서브클래스와 구분했음을 알 수 있습니다.

Sub_class.java라는 이름의 파일에 프로그램을 복사하여 붙여넣습니다.

라이브 데모
class Super_class {
   int num = 20;

   // display method of superclass
   public void display() {
      System.out.println("This is the display method of superclass");
   }
}

public class Sub_class extends Super_class {
   int num = 10;

   // display method of sub class
   public void display() {
      System.out.println("This is the display method of subclass");
   }

   public void my_method() {
      // Instantiating subclass
      Sub_class sub = new Sub_class();

      // Invoking the display() method of sub class
      sub.display();

      // Invoking the display() method of superclass
      super.display();

      // printing the value of variable num of subclass
      System.out.println("value of the variable named num in sub class:"+ sub.num);

      // printing the value of variable num of superclass
      System.out.println("value of the variable named num in super class:"+ super.num);
   }

   public static void main(String args[]) {
      Sub_class obj = new Sub_class();
      obj.my_method();
   }
}

다음 구문을 사용하여 위의 코드를 컴파일하고 실행합니다.

javac Super_Demo
java Super

프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다 -

출력

This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20

수퍼클래스 생성자 호출

클래스가 다른 클래스의 속성을 상속하는 경우 하위 클래스는 자동으로 상위 클래스의 기본 생성자를 획득합니다. 그러나 슈퍼클래스의 매개변수화된 생성자를 호출하려면 아래와 같이 super 키워드를 사용해야 합니다.

super(values);

샘플 코드

이 섹션에 제공된 프로그램은 super 키워드를 사용하여 슈퍼클래스의 매개변수화된 생성자를 호출하는 방법을 보여줍니다. 이 프로그램은 슈퍼클래스와 서브클래스를 포함합니다. 슈퍼클래스는 정수 값을 허용하는 매개변수화된 생성자를 포함하고 슈퍼 키워드를 사용하여 슈퍼클래스의 매개변수화된 생성자를 호출합니다.

Subclass.java

라는 이름의 파일에 다음 프로그램을 복사하여 붙여넣습니다.

라이브 데모
class Superclass {
   int age;

   Superclass(int age) {
      this.age = age; 		 
   }

   public void getAge() {
      System.out.println("The value of the variable named age in super class is: " +age);
   }
}

public class Subclass extends Superclass {
   Subclass(int age) {
      super(age);
   }

   public static void main(String args[]) {
      Subclass s = new Subclass(24);
      s.getAge();
   }
}

다음 구문을 사용하여 위의 코드를 컴파일하고 실행합니다.

javac Subclass
java Subclass

프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다 -

출력

The value of the variable named age in super class is: 24

IS-A 관계

IS-A는 다음과 같이 말하는 방식입니다. 이 개체는 해당 개체의 유형입니다. 확장 방법을 살펴보겠습니다. 키워드는 상속을 달성하는 데 사용됩니다.

public class Animal {
}

public class Mammal extends Animal {
}

public class Reptile extends Animal {
}

public class Dog extends Mammal {
}

이제 위의 예를 기반으로 객체 지향 용어로 다음이 참입니다 -

이제 IS-관계를 고려하면 다음과 같이 말할 수 있습니다.

extends 키워드를 사용하면 하위 클래스는 상위 클래스의 개인 속성을 제외한 상위 클래스의 모든 속성을 상속할 수 있습니다.

인스턴스 연산자를 사용하여 Mammal이 실제로 Animal임을 확신할 수 있습니다.

라이브 데모
class Animal {
}

class Mammal extends Animal {
}

class Reptile extends Animal {
}

public class Dog extends Mammal {

   public static void main(String args[]) {
      Animal a = new Animal();
      Mammal m = new Mammal();
      Dog d = new Dog();

      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
   }
}

이것은 다음 결과를 생성합니다 -

출력

true
true
true

확장에 대해 잘 알고 있기 때문에 키워드를 사용하여 구현하는 방법을 살펴보겠습니다. 키워드는 IS-A 관계를 얻는 데 사용됩니다.

일반적으로 구현 키워드는 인터페이스의 속성을 상속하기 위해 클래스와 함께 사용됩니다. 인터페이스는 클래스에 의해 확장될 수 없습니다.

public interface Animal {
}

public class Mammal implements Animal {
}

public class Dog extends Mammal {
}

instanceof 키워드

instanceof를 사용하겠습니다. 연산자를 사용하여 포유류가 실제로 동물인지, 개가 실제로 동물인지 확인합니다.

라이브 데모
interface Animal{}
class Mammal implements Animal{}

public class Dog extends Mammal {

   public static void main(String args[]) {
      Mammal m = new Mammal();
      Dog d = new Dog();

      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
   }
}

이것은 다음 결과를 생성합니다 -

출력

true
true
true

HAS-A 관계

이러한 관계는 주로 사용을 기반으로 합니다. 이것은 특정 클래스가 HAS-A인지 여부를 결정합니다. 확실한 것. 이 관계는 코드의 중복과 버그를 줄이는 데 도움이 됩니다.

예를 살펴보겠습니다 -

public class Vehicle{}
public class Speed{}

public class Van extends Vehicle {
   private Speed sp;
} 

이것은 Van HAS-A Speed ​​클래스를 보여줍니다. Speed에 대한 별도의 클래스를 가짐으로써 속도에 속하는 전체 코드를 Van 클래스에 넣을 필요가 없으므로 여러 애플리케이션에서 Speed ​​클래스를 재사용할 수 있습니다.

객체 지향 기능에서 사용자는 실제 작업을 수행하는 객체에 대해 신경 쓸 필요가 없습니다. 이를 달성하기 위해 Van 클래스는 Van 클래스 사용자에게 구현 세부 정보를 숨깁니다. 따라서 기본적으로 사용자는 Van 클래스에게 특정 작업을 수행하도록 요청하고 Van 클래스는 자체적으로 작업을 수행하거나 다른 클래스에게 작업을 수행하도록 요청합니다.

상속 유형

상속에는 아래와 같이 다양한 유형이 있습니다.

기억해야 할 매우 중요한 사실은 Java가 다중 상속을 지원하지 않는다는 것입니다. 이것은 클래스가 둘 이상의 클래스를 확장할 수 없음을 의미합니다. 따라서 다음은 불법입니다 -

public class extends Animal, Mammal{} 

그러나 클래스는 하나 이상의 인터페이스를 구현할 수 있으므로 Java가 다중 상속의 불가능성을 제거하는 데 도움이 되었습니다.


java

  1. 자바 최종 키워드
  2. 자바 instanceof 연산자
  3. 자바 중첩 정적 클래스
  4. 자바 익명 클래스
  5. 자바 싱글톤 클래스
  6. 자바 리플렉션
  7. 자바 ObjectOutputStream 클래스
  8. 자바 제네릭
  9. 자바 파일 클래스
  10. C# - 상속