logo

Java의 추상 클래스

Java에서는 abstract 키워드를 사용하여 추상 클래스를 선언합니다. 추상 메서드와 비추상 메서드(본문이 있는 메서드)가 모두 있을 수 있습니다. Abstract는 Java의 클래스 및 메소드에 적용할 수 있는 Java 수정자이지만 변수용이 아님 . 이번 글에서는 자바에서 추상 클래스를 사용하는 방법을 배워보겠습니다.

Java의 추상 클래스란 무엇입니까?

Java 추상 클래스는 자체적으로 시작할 수 없는 클래스이므로 해당 속성을 사용하려면 다른 클래스에서 서브클래싱해야 합니다. 추상 클래스는 클래스 정의에서 abstract 키워드를 사용하여 선언됩니다.

추상 클래스의 그림

abstract class Shape  {  int color;  // An abstract function  abstract void draw(); }>

Java에서는 다음과 같은 일부 중요한 관찰 추상 클래스에 대한 내용은 다음과 같습니다.



  1. 추상 클래스의 인스턴스를 만들 수 없습니다.
  2. 생성자가 허용됩니다.
  3. 추상 메소드 없이도 추상 클래스를 가질 수 있습니다.
  4. 있을 수 있습니다 최종 방법 추상 클래스에서는 클래스(추상 클래스)의 추상 메서드를 final로 선언할 수 없습니다. 또는 더 간단한 용어로 final 메서드는 오류가 발생하므로 자체적으로 추상화할 수 없습니다. 수정자의 잘못된 조합: abstract 및 final
  5. 추상 클래스에서 정적 메소드를 정의할 수 있습니다.
  6. 우리는 추상 키워드 선언을 위해 최상위 클래스(외부 클래스) 및 내부 클래스 추상적으로
  7. 만약 수업 적어도 포함 하나의 추상 메소드 그런 다음 필수는 클래스를 추상으로 선언해야 합니다.
  8. 만약 어린이 수업 모든 추상 메서드에 대한 구현을 제공할 수는 없습니다. 상위 클래스 그럼 우리는 이렇게 선언해야 해 추상적인 하위 클래스 다음 레벨 Child 클래스는 나머지 추상 메소드에 대한 구현을 제공해야 합니다.

Java 추상 클래스의 예

1. Abstract 메소드를 갖는 Abstract 클래스의 예

다음은 위 주제의 구현입니다.

자바




// Abstract class> abstract> class> Sunstar {> >abstract> void> printInfo();> }> // Abstraction performed using extends> class> Employee>extends> Sunstar {> >void> printInfo()> >{> >String name =>'avinash'>;> >int> age =>21>;> >float> salary =>222>.2F;> >System.out.println(name);> >System.out.println(age);> >System.out.println(salary);> >}> }> // Base class> class> Base {> >public> static> void> main(String args[])> >{> >Sunstar s =>new> Employee();> >s.printInfo();> >}> }>

>

>

산출

avinash 21 222.2>

2. 생성자, 데이터 멤버, 메소드를 갖는 추상 클래스

추상 클래스가 가질 수 있는 요소

  • 데이터 멤버
  • 추상적인 방법
  • 메소드 본문(비추상 메소드)
  • 건설자
  • 메인() 메소드.

다음은 위 주제의 구현입니다.

자바




// Java Program to implement Abstract Class> // having constructor, data member, and methods> import> java.io.*;> abstract> class> Subject {> >Subject() {> >System.out.println(>'Learning Subject'>);> >}> > >abstract> void> syllabus();> > >void> Learn(){> >System.out.println(>'Preparing Right Now!'>);> >}> }> class> IT>extends> Subject {> >void> syllabus(){> >System.out.println(>'C , Java , C++'>);> >}> }> class> GFG {> >public> static> void> main(String[] args) {> >Subject x=>new> IT();> > >x.syllabus();> >x.Learn();> >}> }>

>

>

산출

Learning Subject C , Java , C++ Preparing Right Now!>

추상 클래스의 속성

이러한 관찰에 대해 자세히 설명하고 다음과 같이 깨끗한 Java 프로그램을 사용하여 이를 정당화해 보겠습니다.

관찰 1

Java에서는 C++에서와 마찬가지로 추상 클래스의 인스턴스를 만들 수 없지만 추상 클래스 유형에 대한 참조를 가질 수 있습니다. 클린자바 프로그램을 통해서 보면 아래와 같습니다.

자바




// Java Program to Illustrate> // that an instance of Abstract> // Class can not be created> // Class 1> // Abstract class> abstract> class> Base {> >abstract> void> fun();> }> // Class 2> class> Derived>extends> Base {> >void> fun()> >{> >System.out.println(>'Derived fun() called'>);> >}> }> // Class 3> // Main class> class> Main {> >// Main driver method> >public> static> void> main(String args[])> >{> >// Uncommenting the following line will cause> >// compiler error as the line tries to create an> >// instance of abstract class. Base b = new Base();> >// We can have references of Base type.> >Base b =>new> Derived();> >b.fun();> >}> }>

>

>

산출

nfa를 dfa로 변환하다
Derived fun() called>

관찰 2

C++와 마찬가지로 추상 수업 포함할 수 있다 생성자 자바에서. 그리고 상속된 클래스의 인스턴스가 생성될 때 추상 클래스의 생성자가 호출됩니다. 아래 프로그램에서 다음과 같이 표시됩니다.

예:

자바




// Java Program to Illustrate Abstract Class> // Can contain Constructors> // Class 1> // Abstract class> abstract> class> Base {> >// Constructor of class 1> >Base()> >{> >// Print statement> >System.out.println(>'Base Constructor Called'>);> >}> >// Abstract method inside class1> >abstract> void> fun();> }> // Class 2> class> Derived>extends> Base {> >// Constructor of class2> >Derived()> >{> >System.out.println(>'Derived Constructor Called'>);> >}> >// Method of class2> >void> fun()> >{> >System.out.println(>'Derived fun() called'>);> >}> }> // Class 3> // Main class> class> GFG {> >// Main driver method> >public> static> void> main(String args[])> >{> >// Creating object of class 2> >// inside main() method> >Derived d =>new> Derived();> >d.fun();> >}> }>

>

>

산출

Base Constructor Called Derived Constructor Called Derived fun() called>

관찰 3

Java에서는 다음을 가질 수 있습니다. 추상 메서드가 없는 추상 클래스 . 이를 통해 우리는 인스턴스화할 수는 없지만 상속만 가능한 클래스 생성 . 클린 자바 프로그램의 도움으로 아래와 같이 표시됩니다.

예:

자바




// Java Program to illustrate Abstract class> // Without any abstract method> // Class 1> // An abstract class without any abstract method> abstract> class> Base {> >// Demo method. This is not an abstract method.> >void> fun()> >{> >// Print message if class 1 function is called> >System.out.println(> >'Function of Base class is called'>);> >}> }> // Class 2> class> Derived>extends> Base {> >// This class only inherits the Base class methods and> >// properties> }> // Class 3> class> Main {> >// Main driver method> >public> static> void> main(String args[])> >{> >// Creating object of class 2> >Derived d =>new> Derived();> >// Calling function defined in class 1 inside main()> >// with object of class 2 inside main() method> >d.fun();> >}> }>

>

>

산출

Function of Base class is called>

관찰 4

추상 클래스도 가능합니다. 결정적인 행동 양식 (재정의할 수 없는 메서드)

예:

자바




// Java Program to Illustrate Abstract classes> // Can also have Final Methods> // Class 1> // Abstract class> abstract> class> Base {> >final> void> fun()> >{> >System.out.println(>'Base fun() called'>);> >}> }> // Class 2> class> Derived>extends> Base {> > }> // Class 3> // Main class> class> GFG {> >// Main driver method> >public> static> void> main(String args[])> >{> >{> >// Creating object of abstract class> >Base b =>new> Derived();> >// Calling method on object created above> >// inside main method> >b.fun();> >}> >}> }>

>

>

산출

Base fun() called>

관찰 5

추상 Java 클래스의 경우 객체 생성이 허용되지 않습니다. 즉, 추상 클래스 인스턴스화가 불가능합니다.

자바




// Java Program to Illustrate Abstract Class> // Main class> // An abstract class> abstract> class> GFG {> >// Main driver method> >public> static> void> main(String args[])> >{> >// Trying to create an object> >GFG gfg =>new> GFG();> >}> }>

>

>

산출:

추상 수업

관찰 6

인터페이스와 유사 추상 클래스에서 정적 메서드를 정의할 수 있습니다. 저것 객체 없이 독립적으로 호출할 수 있습니다.

자바




// Java Program to Illustrate> // Static Methods in Abstract> // Class Can be called Independently> // Class 1> // Abstract class> abstract> class> Helper {> >// Abstract method> >static> void> demofun()> >{> >// Print statement> >System.out.println(>'Geeks for Geeks'>);> >}> }> // Class 2> // Main class extending Helper class> public> class> GFG>extends> Helper {> >// Main driver method> >public> static> void> main(String[] args)> >{> >// Calling method inside main()> >// as defined in above class> >Helper.demofun();> >}> }>

>

>

산출

Geeks for Geeks>

관찰 7

우리는 추상 키워드 최상위 클래스(외부 클래스)와 내부 클래스를 추상으로 선언하기 위해

자바




import> java.io.*;> abstract> class> B {> >// declaring inner class as abstract with abstract> >// method> >abstract> class> C {> >abstract> void> myAbstractMethod();> >}> }> class> D>extends> B {> >class> E>extends> C {> >// implementing the abstract method> >void> myAbstractMethod()> >{> >System.out.println(> >'Inside abstract method implementation'>);> >}> >}> }> public> class> Main {> >public> static> void> main(String args[])> >{> >// Instantiating the outer class> >D outer =>new> D();> >// Instantiating the inner class> >D.E inner = outer.>new> E();> >inner.myAbstractMethod();> >}> }>

>

>

산출

Inside abstract method implementation>

관찰 8

만약 클래스에는 적어도 하나의 추상 메서드가 포함되어 있습니다. 그 다음에 클래스를 추상 클래스로 선언해야 합니다. 그렇지 않으면 컴파일 타임 오류가 발생합니다. 클래스에 하나 이상의 추상 메소드가 포함되어 있으면 해당 클래스에 대한 구현이 완료되지 않으므로 이러한 부분 클래스에 대한 객체 생성을 제한하기 위해 객체를 생성하는 것은 권장되지 않습니다. 우리는 사용 추상 키워드.

자바




/*package whatever //do not write package name here */> import> java.io.*;> // here if we remove the abstract> // keyword then we will get compile> // time error due to abstract method> abstract> class> Demo {> >abstract> void> m1();> }> class> Child>extends> Demo {> >public> void> m1()> >{> >System.out.print(>'Hello'>);> >}> }> class> GFG {> >public> static> void> main(String[] args)> >{> >Child c =>new> Child();> >c.m1();> >}> }>

>

>

산출

Hello>

관찰 9

만약 어린이 클래스가 Parent 클래스의 모든 추상 메서드에 대한 구현을 제공할 수 없으면 해당 Child 클래스를 추상으로 선언하여 다음 수준 Child 클래스가 나머지 추상 메서드에 대한 구현을 제공해야 합니다.

자바




// Java Program to demonstrate> // Observation> import> java.io.*;> abstract> class> Demo {> >abstract> void> m1();> >abstract> void> m2();> >abstract> void> m3();> }> abstract> class> FirstChild>extends> Demo {> >public> void> m1() {> >System.out.println(>'Inside m1'>);> >}> }> class> SecondChild>extends> FirstChild {> >public> void> m2() {> >System.out.println(>'Inside m2'>);> >}> >public> void> m3() {> >System.out.println(>'Inside m3'>);> >}> }> class> GFG {> >public> static> void> main(String[] args)> >{> >// if we remove the abstract keyword from FirstChild> >// Class and uncommented below obj creation for> >// FirstChild then it will throw> >// compile time error as did't override all the> >// abstract methods> >// FirstChild f=new FirstChild();> >// f.m1();> >SecondChild s =>new> SecondChild();> >s.m1();> >s.m2();> >s.m3();> >}> }>

>

삽입 정렬 자바
>

산출

Inside m1 Inside m2 Inside m3>

C++에서 클래스에 하나 이상의 순수 가상 함수 , 그러면 클래스가 추상화됩니다. C++와 달리 Java에서는 클래스를 추상화하기 위해 별도의 키워드 추상을 사용합니다.

결론

이 기사에서 기억해야 할 사항은 다음과 같습니다.

  • 추상 클래스는 자체적으로 시작할 수 없는 클래스이므로 해당 속성을 사용하려면 다른 클래스에서 서브클래싱해야 합니다.
  • 추상 키워드를 사용하여 추상 클래스를 만들 수 있습니다.
  • 추상 메소드 없이도 추상 클래스를 가질 수 있습니다.

추상 수업 FAQ

1. Java의 추상 클래스란 무엇입니까?

Java의 추상 클래스는 자체적으로 시작할 수는 없지만 다른 클래스의 하위 클래스로 사용할 수 있는 클래스입니다.

2. 추상수업의 목적은 무엇인가요?

추상 클래스의 주요 목적은 다른 많은 클래스가 파생될 수 있는 기본 클래스를 만드는 것입니다.

3. 추상수업의 가장 큰 장점은 무엇인가요?

추상 클래스는 Java에 숨어 있는 데이터를 제공합니다.

4. 추상 클래스가 인터페이스보다 빠른 이유는 무엇입니까?

추상 클래스는 Java에서 재정의된 메서드를 호출하기 전에 인터페이스를 검색해야 하는 반면 추상 클래스는 직접 사용할 수 있으므로 인터페이스보다 빠릅니다.

또한 읽어보세요