寒假的Java学习笔记总结1

1.抽象类(用abstract关键字修饰声明)

(1)包含抽象方法的抽象类也必须用abstract关键字来声明。

(2)抽象类中来声明的抽象构造方法必须在子类中调用(抽象方法必须包含于抽象类)。

抽象类的特点:

(1)不能直接被实例化,也不能直接用new关键字来产生对象。

(2)只需要声明,不需实现。

(3)抽象子类必须覆盖所有抽象方法后才能被实例化。

(4)含有抽象方法的类必须被声明为抽象类。

以下代码是抽象类的应用

abstract class Person
{
 String name;
 int age;
 String occupation;
 //声明一个抽象方法talk;
 public abstract String talk();
}
//Student继承自Person类
class Student extends Person
{
 public Student(String name,int age,String occupation)
 {
  this.name=name;
  this.age=age;
  this.occupation=occupation;
 }
 //覆写talk()
 public String talk()
 {
  return "学生--姓名:"+this.name+",年龄:"+this.age+",职业:"+this.occupation+"!";
 }
}
//Worker继承自Person类
class Worker extends Person
{
 public Worker(String name,int age,String occupation)
 {
  this.name=name;
  this.age=age;
  this.occupation=occupation;
 }
 //覆写talk()
 public String talk()
 {
  return "工人--姓名:"+this.name+",年龄:"+this.age+",职业:"+this.occupation+"!";
 }
}
public class Java {

 public static void main(String args[])
 {
  Student s=new Student("陈昆明",22,"学生");
  Worker w=new Worker("李四",52,"工人");
  System.out.println(s.talk());
  System.out.println(w.talk());
 }
}

运行结果:

2.接口

(1)格式

interface 接口名称

{

        final 数据类型 成员名称=常量             //数据成员必须赋初值

        abstract(抽象方法声明时关键字可以省略)   返回值数据名称   方法名(参数)     //抽象方法

}

class 类名称 implement 接口A,接口B

{······}

(注1:抽象方法里没有定义方法的主体,借口哦与一般类一样,但是方法必须为抽象方法)

(注2:与抽象方法不同的是,一个类可以继承多个接口。再覆盖抽象方法时,在子类中不用abstract声明。)

接口的应用代码:

interface Person
{
 String name="Left涅槃";
 int age=22;
 String occupation="学生";
 //声明一个抽象方法talk()
 public abstract String talk();
}
//Student类实现Person类
class Student implements Person
{
 //覆写talk()方法
 public String talk()
 {
  return "学生-->姓名:"+name+",年龄:"+age+",职业:"+occupation+"!";
 }
}
public class Javajeikou1 {
 public static void main(String args[])
 {
  Student s=new Student();
  System.out.println(s.talk());
 }
}

运行截图:

原文地址:https://www.cnblogs.com/CkmIT/p/6385975.html